web

package
v1.5.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 7, 2026 License: MIT Imports: 29 Imported by: 1

Documentation

Index

Constants

View Source
const (
	KeyUserID      = "uid"
	KeyLevel       = "level"
	KeyRoleID      = "role_id"
	KeyUsername    = "username"
	KeyTokenString = "token"
)

为确保兼容性,以下值不可更改 uid 和 role_id 是 int 类型,其余未明确标识的是字符串类型

View Source
const DefaultBodyLimit = 100
View Source
const ResponseErr = "responseErr"

Variables

This section is empty.

Functions

func AbortWithStatusJSON

func AbortWithStatusJSON(c ResponseWriter, err error, fn ...WithData)

func AddHead

func AddHead() gin.HandlerFunc

func AuthLevel

func AuthLevel(level int, ignoreFn ...IngoreOption) gin.HandlerFunc

AuthLevel 类似日志,可以使用 IgnorePrefix,IgnoreMethod,IgnoreBool,IgoreContains 等方法 用于限制特定级别的访问,当访问级别大于 level 时响应权限不足,<= level 时放行 等级从1开始,等级越小,权限越大

func AuthMiddleware

func AuthMiddleware(secret string) gin.HandlerFunc

AuthMiddleware 鉴权

func CacheControlMaxAge

func CacheControlMaxAge(second int, ignoreFn ...IngoreOption) gin.HandlerFunc

WebCache 主要用于缓存静态资源 Cache-Control: max-age=3600 # 缓存1小时 Cache-Control: no-cache # 每次都需要验证 Cache-Control: no-store # 完全不缓存 Cache-Control: private # 只允许浏览器缓存 Cache-Control: public # 允许中间代理缓存

func CountGoroutines

func CountGoroutines(d time.Duration, num uint8)

CountGoroutines 协程数量,间隔 duration 记录一次

func CustomMethods added in v1.5.1

func CustomMethods(g gin.IRouter, relativePath string, data map[string]func(*gin.Context))

CustomMethods 自定义行为封装,其实现方式建议使用在叶子节点的路由上 一个最佳实践是 2~3 层路由上,例如 /rooms/:name/sound

设计参考谷歌 restful 设计指南: https://google-cloud.gitbook.io/api-design-guide/custom_methods#http-ying-she

示例: group := r.Group("/rooms", auth) CustomMethods(group, "/:name/sound", map[string]func(*gin.Context){ "muted": web.WrapH(api.muteRoom), "unmuted": web.WrapH(api.unmuteRoom), }) 当找不到对应定义时,会响应 404 状态码

func EtagHandler

func EtagHandler(ignoreFn ...IngoreOption) gin.HandlerFunc

EtagHandler 添加 ETag 头,用于缓存静态资源 不适合大文件场景,每次都是实时计算的

func Fail

func Fail(c ResponseWriter, err error, fn ...WithData)

Fail 通用错误返回

func GetBaseURL

func GetBaseURL(req *http.Request) string

GetBaseURL 提取请求地址 例如 http://127.0.0.1:8080/health 提取出 http://127.0.0.1:8080

func GetHost

func GetHost(req *http.Request) string

GetHost 提取主机 IP 或域名 例如 http://127.0.0.1:8080/health 提取出 127.0.0.1

func GetInt added in v1.3.8

func GetInt(c Geter, key string) int

func GetLevel added in v1.2.11

func GetLevel(c Geter) int

func GetRoleID added in v1.3.7

func GetRoleID(c Geter) int

GetRole 获取用户角色

func GetScheme added in v1.3.10

func GetScheme(req *http.Request) string

GetScheme 获取请求协议 例如 http://127.0.0.1:8080/health 提取出 http

func GetToken added in v1.3.9

func GetToken(c Geter) string

GetToken 获取 token

func GetUID

func GetUID(c Geter) int

GetUID 获取用户 ID

func GetUsername

func GetUsername(c Geter) string

GetUsername 获取用户名

func HanddleJSONErr

func HanddleJSONErr(err error) error

func HandlerResponseMsg

func HandlerResponseMsg(resp http.Response) error

HandlerResponseMsg 获取响应的结果

func IDRateLimiter added in v1.5.2

func IDRateLimiter(r rate.Limit, b int, ttl time.Duration) func(identifier string) bool

IDRateLimiter 限流器

func IPRateLimiterForGin

func IPRateLimiterForGin(r rate.Limit, b int, ignoreFn ...IngoreOption) gin.HandlerFunc

IPRateLimiter IP 限流器 可以在 filter 中执行 AbortWithStatusJSON 相关操作,用于替代默认行为 r 每秒允许发生的事件 b 最大桶容量,处理突发事件 example:

IPRateLimiterForGin(1, 10, IgnorePrefix("/api/v1/login"))

func IsRelease added in v1.3.12

func IsRelease() bool

IsRelease 是否是生产环境

func Limit

func Limit(v, minV, maxV int) int

Limit 限制数值在 min 和 max 之间

func LimitContentLength added in v1.3.10

func LimitContentLength(limit int, ignoreFn ...IngoreOption) gin.HandlerFunc

LimitContentLength 限制请求体大小,比如限制 1MB,可以传入 1024*1024

func Logger

func Logger(ignoreFn ...IngoreOption) gin.HandlerFunc

Logger 记录 http 请求日志 入参是忽略函数,返回 true 则忽略,比如网页请求可以忽略

func LoggerWithBody added in v1.3.0

func LoggerWithBody(limit int, ignoreFn ...IngoreOption) gin.HandlerFunc

LoggerWithBody 记录请求体与响应体,通常用于开发调试 日志级别是 debug,即没有忽略也可能因为日志级别不打印内容 limit 用于限制打印数据的大小,防止超大请求体或响应体

func LoggerWithUseTime added in v1.3.3

func LoggerWithUseTime(maxLimit time.Duration, ignoreFn ...IngoreOption) gin.HandlerFunc

LoggerWithUseTime 记录请求用时 >= maxLimit 时,记录 warn 级别日志

func Metrics

func Metrics() gin.HandlerFunc

Metrics ...

func MustTraceID

func MustTraceID(ctx context.Context) string

func NewToken

func NewToken(data map[string]any, secret string, opts ...TokenOptions) (string, error)

NewToken 创建 token 秘钥不能为空,默认过期时间是 6 个小时 WithExpires() 指定过期时间

func Offset

func Offset(page, size int) int

func RateLimiter

func RateLimiter(r rate.Limit, b int, ignoreFn ...IngoreOption) gin.HandlerFunc

RateLimiter 限流器 r 每秒允许发生的事件 b 最大桶容量,处理突发事件

func RecordResponse

func RecordResponse() gin.HandlerFunc

func Recover

func Recover() gin.HandlerFunc

Recover from panics and converts the panic to an error so it is reported in Metrics and handled in Errors.

func SendChunk

func SendChunk(ch <-chan Chunk, c *gin.Context)

SendChunk 发送分块数据

func SendChunkPro

func SendChunkPro(ch <-chan Chunk, c *gin.Context)

SendChunkPro 高性能版

func SendSSE

func SendSSE(ch <-chan EventMessage, c *gin.Context)

func SetDebug added in v1.2.0

func SetDebug()

SetDebug 设置为开发环境 接口输出 details 信息,details 会包含敏感信息

func SetRelease

func SetRelease()

SetRelease 设置为生产环境 接口不在输出 details 信息

func SetTraceID

func SetTraceID(ctx *gin.Context, id string)

func SetupMutexProfile

func SetupMutexProfile(rate int)

SetupMutexProfile 启用互斥锁采样,rate=1 开启采样, rate<=0 关闭采样

func SetupPProf

func SetupPProf(r gin.IRouter, ips *[]string)

func Success

func Success(c HTTPContext, bean any)

Success 通用成功返回

func TraceID

func TraceID(ctx context.Context) (string, bool)

func WrapH added in v1.3.15

func WrapH[I any, O any](fn func(*gin.Context, *I) (O, error)) gin.HandlerFunc

WrapH 让函数更专注于业务,一般入参和出参应该是指针类型 没有入参时,应该使用 *struct{}

func WrapHs added in v1.3.15

func WrapHs[I any, O any](fn func(*gin.Context, *I) (O, error), mid ...gin.HandlerFunc) []gin.HandlerFunc

WrapHs 包装业务处理函数的同时,支持多个中间件

func XForwardedPrefix added in v1.3.21

func XForwardedPrefix(req *http.Request, path string) string

XForwardedPrefix 解决反向代理路由问题

Types

type BufferWriter added in v1.3.0

type BufferWriter struct {
	gin.ResponseWriter
	// contains filtered or unexported fields
}

func (*BufferWriter) Unwrap added in v1.3.0

func (w *BufferWriter) Unwrap() http.ResponseWriter

func (*BufferWriter) Write added in v1.3.0

func (w *BufferWriter) Write(b []byte) (int, error)

type Chunk

type Chunk struct {
	Total   int    `json:"total"`
	Current int    `json:"current"`
	Success int    `json:"success"`
	Failure int    `json:"failure"`
	Err     string `json:"err,omitempty"`
}

type Claims

type Claims struct {
	Data map[string]any
	jwt.RegisteredClaims
}

Claims ... 注意 int 类型在 json 反序列化后会是 float64 即通过 gin.context 获取的数字参数,都要用 GetFloat64

func ParseToken

func ParseToken(tokenString string, secret string) (*Claims, error)

ParseToken 解析 token

type ClaimsData added in v1.3.5

type ClaimsData map[string]any

func NewClaimsData added in v1.3.5

func NewClaimsData() ClaimsData

NewClaimsData 提供了一些默认的设置,例如 SetUserID 提供的不够用时,请使用 Set(k,v),并实现对应的 GetK() 函数 也可以匿名嵌套实现更多

func (ClaimsData) Set added in v1.3.5

func (c ClaimsData) Set(key string, value any) ClaimsData

func (ClaimsData) SetLevel added in v1.3.5

func (c ClaimsData) SetLevel(level int) ClaimsData

func (ClaimsData) SetRoleID added in v1.3.8

func (c ClaimsData) SetRoleID(roleID int) ClaimsData

func (ClaimsData) SetUserID added in v1.3.5

func (c ClaimsData) SetUserID(uid int) ClaimsData

func (ClaimsData) SetUsername added in v1.3.5

func (c ClaimsData) SetUsername(username string) ClaimsData

type DateFilter

type DateFilter struct {
	StartMs int64 `form:"start_ms"`
	EndMs   int64 `form:"end_ms"`
}

DateFilter 日期区间过滤

func (DateFilter) DefaultEndAt

func (d DateFilter) DefaultEndAt(date time.Time) time.Time

DefaultEndAt 当为零值或不符合规则时,返回提供的默认值

func (DateFilter) DefaultStartAt

func (d DateFilter) DefaultStartAt(date time.Time) time.Time

DefaultStartAt 当为零值或不符合规则时,返回提供的默认值

func (DateFilter) EndAt

func (d DateFilter) EndAt() time.Time

EndAt 结束时间

func (DateFilter) StartAt

func (d DateFilter) StartAt() time.Time

StartAt 开始时间

type EtagWriter

type EtagWriter struct {
	gin.ResponseWriter
	// contains filtered or unexported fields
}

func (*EtagWriter) Unwrap

func (w *EtagWriter) Unwrap() http.ResponseWriter

func (*EtagWriter) Write

func (w *EtagWriter) Write(b []byte) (int, error)

type Event

type Event struct {
	ID    string
	Event string
	Data  []byte
}

type EventMessage

type EventMessage struct {
	// contains filtered or unexported fields
}

func NewEventMessage

func NewEventMessage(event string, data map[string]any) *EventMessage

type Geter added in v1.4.0

type Geter interface {
	GetString(key any) string
	Get(key any) (value any, exists bool)
}

type GoroutineNum

type GoroutineNum struct {
	Time string `json:"time"`
	Num  int    `json:"num"`
}

type HTTPContext

type HTTPContext interface {
	JSON(int, any)
	Header(key, value string)
	context.Context
}

type IngoreOption added in v1.3.17

type IngoreOption func(*gin.Context) bool

func IgnoreBool added in v1.3.2

func IgnoreBool(v bool) IngoreOption

IgnoreBool 忽略指定值

func IgnoreMethod added in v1.3.4

func IgnoreMethod(method string) IngoreOption

IgnoreMethod 忽略指定请求方式的请求,一般用于忽略 options

func IgnorePath added in v1.3.18

func IgnorePath(path ...string) IngoreOption

IgnorePath 忽略指定路由

func IgnorePrefix added in v1.3.0

func IgnorePrefix(prefix ...string) IngoreOption

IgnorePrefix 忽略指定路由前缀

func IgoreContains added in v1.3.0

func IgoreContains(substrs ...string) IngoreOption

IgoreContains 忽略包含的路由

type PageOutput

type PageOutput[T any] struct {
	Items []T   `json:"items"`
	Total int64 `json:"total"`
}

PageOutput 分页数据

type PagerFilter

type PagerFilter struct {
	Page         int      `form:"page"`
	Size         int      `form:"size"`
	Sort         string   `form:"sort"`
	SortSafelist []string `json:"-"`
}

PagerFilter 分页过滤

func NewPagerFilterMaxSize

func NewPagerFilterMaxSize() PagerFilter

func (PagerFilter) Limit

func (f PagerFilter) Limit() int

Limit 每页 1~10000 区间

func (PagerFilter) MustSortColumn

func (f PagerFilter) MustSortColumn() string

MustSortColumn 忽略安全问题 失败如果是空串,则不做排序处理

func (PagerFilter) Offset

func (f PagerFilter) Offset() int

Offset 计算偏离数值

func (PagerFilter) SortColumn

func (f PagerFilter) SortColumn() (string, bool)

SortColumn 通过对 SortColumn 设置值,仅对允许的值做排序处理

func (PagerFilter) SortDirection

func (f PagerFilter) SortDirection() string

SortDirection 如果 sort 携带负号返回倒序,否则返回正序

type ResponseMsg

type ResponseMsg struct {
	Msg string `json:"msg"`
}

type ResponseWriter

type ResponseWriter interface {
	JSON(code int, obj any)
	File(filepath string)
	Set(any, any)
	context.Context
	AbortWithStatusJSON(code int, obj any)
}

ResponseWriter ...

type ResponseWriterWrapper

type ResponseWriterWrapper struct {
	gin.ResponseWriter
	Body *bytes.Buffer // 缓存
}

func (ResponseWriterWrapper) Write

func (w ResponseWriterWrapper) Write(b []byte) (int, error)

func (ResponseWriterWrapper) WriteString

func (w ResponseWriterWrapper) WriteString(s string) (int, error)

type SSE

type SSE struct {
	Headers map[string]string
	// contains filtered or unexported fields
}

SSE 发送事件

使用案例

http.HandleFunc("/stream", func(w http.ResponseWriter, r *http.Request) {
	sse := web.NewSSE(1024, time.Minute)

	go func(){
		defer sse.Close()
		for range 3 {
			sse.Publish(web.Event{
				ID:    uuid.New().String(),
				Event: "ping",
				Data: []byte("pong"),
			})
			time.Sleep(time.Second)
		}
	}()
	sse.ServeHTTP(w, r)
})

func NewSSE

func NewSSE(length int, timeout time.Duration) *SSE

func (*SSE) Close

func (s *SSE) Close()

Close 会确保所有事件被发送完毕

func (*SSE) Publish

func (s *SSE) Publish(v Event)

func (*SSE) ServeHTTP

func (s *SSE) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*SSE) Stop added in v1.5.1

func (s *SSE) Stop()

Stop 会立即停止发送事件,stop 后应该调用 Close()

type ScrollPageOutput added in v1.3.10

type ScrollPageOutput[T any] struct {
	Items []T    `json:"items"`
	Next  string `json:"next"`
}

ScrollPageOutput 滚动翻页

type TokenOptions added in v1.3.5

type TokenOptions func(*Claims)

func WithExpires added in v1.3.8

func WithExpires(duration time.Duration) TokenOptions

WithExpires 设置多久过期

func WithExpiresAt added in v1.3.5

func WithExpiresAt(expiresAt time.Time) TokenOptions

WithExpiresAt 设置指定过期时间

func WithIssuedAt added in v1.3.5

func WithIssuedAt(issuedAt time.Time) TokenOptions

WithIssuedAt 设置签发时间

func WithIssuer added in v1.3.5

func WithIssuer(issuer string) TokenOptions

WithIssuer 设置签发人

func WithNotBefore added in v1.3.5

func WithNotBefore(notBefore time.Time) TokenOptions

WithNotBefore 设置生效时间

type Validator

type Validator struct {
	Errors map[string]string
}

Validator 验证对象是否合法

func NewValidator

func NewValidator() *Validator

NewValidator ...

func (*Validator) AddError

func (v *Validator) AddError(key, message string) *Validator

AddError 添加错误

func (*Validator) Check

func (v *Validator) Check(ok bool, key, message string) *Validator

Check 如果 ok==false,则将 message 写入 errors

func (*Validator) List

func (v *Validator) List() []string

List 验证 !Valid() 后,可获取错误列表

func (*Validator) Result

func (v *Validator) Result() (bool, []string)

Result true 表示没有错误

func (*Validator) Valid

func (v *Validator) Valid() bool

Valid 如果没有错误,返回 true

type WithData

type WithData func(map[string]any)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL