middleware

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Authn

func Authn() gin.HandlerFunc

Authn 是认证中间件,用来从 gin.Context 中提取 token 并验证 token 是否合法, 如果合法则将 token 中的 sub 作为<用户名>存放在 gin.Context 的 XUsernameKey 键中.

func BodyLimit added in v0.2.0

func BodyLimit(maxBytes int64) gin.HandlerFunc

BodyLimit 是一个 Gin 中间件,用来限制请求体大小(单位:字节). 当请求声明了 Content-Length 且超过限制时,直接返回统一错误响应 HTTP 413; 未声明长度(chunked)的请求体由 MaxBytesReader 限制,超限读取会返回错误, 业务绑定通常表现为 400,但内存占用仍被限制在 maxBytes 以内。 maxBytes <= 0 时不做限制,直接放行。

func CORS

func CORS(allowedOrigins ...string) gin.HandlerFunc

CORS 是跨域资源共享中间件,用来处理跨域请求. 不传 allowedOrigins 或显式传 "*" 时允许任意源,但不允许携带凭证; 传入具体 allowedOrigins 时仅回显白名单内的源,并允许携带凭证.

func Cors

func Cors(c *gin.Context)

Cors 是 CORS 的兼容入口,等价于 CORS().

func IsRequestTooLarge added in v0.2.0

func IsRequestTooLarge(err error) bool

IsRequestTooLarge 判断错误是否由 BodyLimit 的 http.MaxBytesReader 触发. 业务绑定(c.ShouldBindJSON 等)收到超限错误时,可据此映射为 413:

if err := c.ShouldBindJSON(&req); err != nil {
    if middleware.IsRequestTooLarge(err) {
        response.Error(c, errno.ErrRequestEntityTooLarge)
        return
    }
    response.Error(c, errno.ErrBind)
    return
}

func NoCache

func NoCache(c *gin.Context)

NoCache 是一个 Gin 中间件,用来禁止客户端缓存 HTTP 请求的返回结果.

func RequestID

func RequestID() gin.HandlerFunc

RequestID 是一个 Gin 中间件,用来在每一个 HTTP 请求的 context, response 中注入 `X-Request-ID` 键值对.

func Secure

func Secure(c *gin.Context)

Secure 是一个 Gin 中间件,用来添加一些安全和资源访问相关的 HTTP 头.

Types

This section is empty.

Jump to

Keyboard shortcuts

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