Documentation
¶
Index ¶
- Constants
- func AbortWithStatusJSON(c ResponseWriter, err error, fn ...WithData)
- func AddHead() gin.HandlerFunc
- func AuthLevel(level int, ignoreFn ...IngoreOption) gin.HandlerFunc
- func AuthMiddleware(secret string) gin.HandlerFunc
- func CacheControlMaxAge(second int, ignoreFn ...IngoreOption) gin.HandlerFunc
- func CountGoroutines(d time.Duration, num uint8)
- func CustomMethods(g gin.IRouter, relativePath string, data map[string]func(*gin.Context))
- func EtagHandler(ignoreFn ...IngoreOption) gin.HandlerFunc
- func Fail(c ResponseWriter, err error, fn ...WithData)
- func GetBaseURL(req *http.Request) string
- func GetHost(req *http.Request) string
- func GetInt(c Geter, key string) int
- func GetLevel(c Geter) int
- func GetRoleID(c Geter) int
- func GetScheme(req *http.Request) string
- func GetToken(c Geter) string
- func GetUID(c Geter) int
- func GetUsername(c Geter) string
- func HanddleJSONErr(err error) error
- func HandlerResponseMsg(resp http.Response) error
- func IDRateLimiter(r rate.Limit, b int, ttl time.Duration) func(identifier string) bool
- func IPRateLimiterForGin(r rate.Limit, b int, ignoreFn ...IngoreOption) gin.HandlerFunc
- func IsRelease() bool
- func Limit(v, minV, maxV int) int
- func LimitContentLength(limit int, ignoreFn ...IngoreOption) gin.HandlerFunc
- func Logger(ignoreFn ...IngoreOption) gin.HandlerFunc
- func LoggerWithBody(limit int, ignoreFn ...IngoreOption) gin.HandlerFunc
- func LoggerWithUseTime(maxLimit time.Duration, ignoreFn ...IngoreOption) gin.HandlerFunc
- func Metrics() gin.HandlerFunc
- func MustTraceID(ctx context.Context) string
- func NewToken(data map[string]any, secret string, opts ...TokenOptions) (string, error)
- func Offset(page, size int) int
- func RateLimiter(r rate.Limit, b int, ignoreFn ...IngoreOption) gin.HandlerFunc
- func RecordResponse() gin.HandlerFunc
- func Recover() gin.HandlerFunc
- func SendChunk(ch <-chan Chunk, c *gin.Context)
- func SendChunkPro(ch <-chan Chunk, c *gin.Context)
- func SendSSE(ch <-chan EventMessage, c *gin.Context)
- func SetDebug()
- func SetRelease()
- func SetTraceID(ctx *gin.Context, id string)
- func SetupMutexProfile(rate int)
- func SetupPProf(r gin.IRouter, ips *[]string)
- func Success(c HTTPContext, bean any)
- func TraceID(ctx context.Context) (string, bool)
- func WrapH[I any, O any](fn func(*gin.Context, *I) (O, error)) gin.HandlerFunc
- func WrapHs[I any, O any](fn func(*gin.Context, *I) (O, error), mid ...gin.HandlerFunc) []gin.HandlerFunc
- func XForwardedPrefix(req *http.Request, path string) string
- type BufferWriter
- type Chunk
- type Claims
- type ClaimsData
- type DateFilter
- type EtagWriter
- type Event
- type EventMessage
- type Geter
- type GoroutineNum
- type HTTPContext
- type IngoreOption
- type PageOutput
- type PagerFilter
- type ResponseMsg
- type ResponseWriter
- type ResponseWriterWrapper
- type SSE
- type ScrollPageOutput
- type TokenOptions
- type Validator
- type WithData
Constants ¶
const ( KeyUserID = "uid" KeyLevel = "level" KeyRoleID = "role_id" KeyUsername = "username" KeyTokenString = "token" )
为确保兼容性,以下值不可更改 uid 和 role_id 是 int 类型,其余未明确标识的是字符串类型
const DefaultBodyLimit = 100
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 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 ¶
CountGoroutines 协程数量,间隔 duration 记录一次
func CustomMethods ¶ added in v1.5.1
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 GetBaseURL ¶
GetBaseURL 提取请求地址 例如 http://127.0.0.1:8080/health 提取出 http://127.0.0.1:8080
func GetHost ¶
GetHost 提取主机 IP 或域名 例如 http://127.0.0.1:8080/health 提取出 127.0.0.1
func GetScheme ¶ added in v1.3.10
GetScheme 获取请求协议 例如 http://127.0.0.1:8080/health 提取出 http
func HanddleJSONErr ¶
func HandlerResponseMsg ¶
HandlerResponseMsg 获取响应的结果
func IDRateLimiter ¶ added in v1.5.2
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 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 MustTraceID ¶
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 SendSSE ¶
func SendSSE(ch <-chan EventMessage, c *gin.Context)
func SetTraceID ¶
func SetupMutexProfile ¶
func SetupMutexProfile(rate int)
SetupMutexProfile 启用互斥锁采样,rate=1 开启采样, rate<=0 关闭采样
func SetupPProf ¶
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
type Claims ¶
type Claims struct {
Data map[string]any
jwt.RegisteredClaims
}
Claims ... 注意 int 类型在 json 反序列化后会是 float64 即通过 gin.context 获取的数字参数,都要用 GetFloat64
type ClaimsData ¶ added in v1.3.5
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 ¶
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 当为零值或不符合规则时,返回提供的默认值
type EtagWriter ¶
type EtagWriter struct {
gin.ResponseWriter
// contains filtered or unexported fields
}
func (*EtagWriter) Unwrap ¶
func (w *EtagWriter) Unwrap() http.ResponseWriter
type EventMessage ¶
type EventMessage struct {
// contains filtered or unexported fields
}
func NewEventMessage ¶
func NewEventMessage(event string, data map[string]any) *EventMessage
type GoroutineNum ¶
type HTTPContext ¶
type IngoreOption ¶ added in v1.3.17
func IgnoreMethod ¶ added in v1.3.4
func IgnoreMethod(method string) IngoreOption
IgnoreMethod 忽略指定请求方式的请求,一般用于忽略 options
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 ¶
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) MustSortColumn ¶
func (f PagerFilter) MustSortColumn() string
MustSortColumn 忽略安全问题 失败如果是空串,则不做排序处理
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) WriteString ¶
func (w ResponseWriterWrapper) WriteString(s string) (int, error)
type SSE ¶
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)
})
type ScrollPageOutput ¶ added in v1.3.10
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 WithNotBefore ¶ added in v1.3.5
func WithNotBefore(notBefore time.Time) TokenOptions
WithNotBefore 设置生效时间