middleware

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2025 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CORS

func CORS(opts ...cors.Option) gin.HandlerFunc

CORS 跨域处理

usage:

  r.Use(middleware.CORS())

	 r.Use(middleware.CORS(
	 	middleware.WithCORSAllowOriginFunc(func(origin string) bool {
	 		//return origin == "https://xxxx.com"
	 		return true
	 	}),
	 	middleware.WithCORSAllowHeaders("X-Custom-Key"),
	 	middleware.WithCORSExposeHeaders("X-Custom-Key"),
	 	middleware.WithCORSMaxAge(24*time.Hour),
	 ))

func HttpCache

func HttpCache(opts ...httpcache.Option) gin.HandlerFunc

HttpCache http 响应缓存

usage:

r.Use(middleware.HttpCache(
	middleware.WithHttpCacheDebug(),
	middleware.WithHttpCacheLogger(global.Log),
	middleware.WithHttpCacheJWTOption(global.JWTOption(false)),
	middleware.WithHttpCacheGlobalDuration(5*time.Minute),
	middleware.WithHttpCacheRedisStore(redis.NewClient(&redis.Options{
		Addr:     global.Config.HttpCache.Addr,
		Password: global.Config.HttpCache.Password,
		DB:       global.Config.HttpCache.DB,
	})),
	middleware.WithHttpCacheGlobalSkipFields("v"),
	middleware.WithHttpCacheRouteSkipFiledPolicy("/user/", true),
))

func HttpContext

func HttpContext() gin.HandlerFunc

HttpContext 注入自定义上下文

usage:

r.Use(middleware.HttpContext())

func HttpLogger

func HttpLogger(opt HttpLoggerOption) gin.HandlerFunc

HttpLogger http 日志中间件; 如果有其他内置日志,则该中间件不操作;内置日志有: HttpPrinter 等

usage:

  r.Use(middleware.HttpLogger(middleware.HttpLoggerOption{
	 	Logger:    global.Log,
	 	OnlyError: global.Config.Log.HttpLogOnlyError,
	 }))

func HttpPrinter

func HttpPrinter(log xlog.XLog) gin.HandlerFunc

HttpPrinter 打印 http 信息中间件;展示 request / response 等信息

usage:

r.Use(middleware.HttpContext(global.Log))

router.Any("/endpoint", middleware.HttpPrinter(global.Log), ping.Controller{}.Endpoint)

func IPRateLimit

func IPRateLimit(limiter *limiter.Limiter) gin.HandlerFunc

IPRateLimit IP限速

func JWTStatefulWith

func JWTStatefulWith(opt *jwt.Option, handler jwt.StatefulStore) gin.HandlerFunc

JWTStatefulWith 有状态的 jwt 鉴权中间件 需要配合 jwt.NewStatefulToken 使用(在用户登录成功后,调用该函数创建token)

usage:

 ra := router.Group(
		"/user",
		middleware.JWTStatefulWith(
			&jwt.Option{
	    		RoleConvert:     NewRole,
	    		RefreshDuration: 0, // 0-不自动刷新
	    		Secret:          []byte(global.Config.App.Secret),
	    	},
			jwtstore.NewSingleRedisStore(global.SessionStoreClient), // 单地登录
		),
		middleware.Roles([]types.IRole{global.RoleBroker, global.RoleStar, global.RoleMember}),
	)

func JWTStatefulWithout

func JWTStatefulWithout(opt *jwt.Option) gin.HandlerFunc

JWTStatefulWithout 有状态的 jwt 鉴权中间件,仅校验 jwt 是否合法,不校验状态 需要配合 jwt.NewStatefulToken 使用(在用户登录成功后,调用该函数创建token)

func JWTWith

func JWTWith(opt *jwt.Option) gin.HandlerFunc

JWTWith jwt 鉴权中间件 在用户登录成功后,配合 jwt.NewToken 生成 token

func RESTFul

func RESTFul(version string) gin.HandlerFunc

RESTFul Restful 标准检测解析中间件

func RESTFulWithIgnores

func RESTFulWithIgnores(version string, ignorePaths ...IgnorePath) gin.HandlerFunc

RESTFulWithIgnores 忽略指定 path 的Restful 标准检测解析中间件 一般,用在部分直接下载或浏览器直接访问的接口

func RateLimit

func RateLimit(key string, limiter *limiter.Limiter) gin.HandlerFunc

RateLimit 限速

func RoleFunc

func RoleFunc(handler gin.HandlerFunc, role httpcontext.IRole, roles ...httpcontext.IRole) gin.HandlerFunc

RoleFunc 角色控制器中间件。 如果用户满足指定角色要求,则调用 handler,并在完成后进入下一个中间件; 如果用户不满足指定角色要求,则直接进入下一个中间件 一般,在同一路由针对不同角色处理逻辑完成不同的场景很实用。

func RoleFuncAbort

func RoleFuncAbort(handler gin.HandlerFunc, role httpcontext.IRole, roles ...httpcontext.IRole) gin.HandlerFunc

RoleFuncAbort 角色控制器独占中间件。 如果用户符合指定角色,则使用调用 handler,并在完成后进入下一个中间件; 如果用户不满足指定角色要求,则中断链路,返回 http status 403 错误

func Session

func Session(keyPairs, secret string, opt SessionOption) gin.HandlerFunc

Session 校验 session keyPairs cookie 键名 secret cookie 存储加密密钥

func SessionWithStore

func SessionWithStore(keyPairs string, store sessions.Store, opt SessionOption) gin.HandlerFunc

SessionWithStore 校验 session keyPairs cookie 键名

func WithCORSAllowHeaders

func WithCORSAllowHeaders(keys ...string) cors.Option

WithCORSAllowHeaders 设置服务器允许客户端在跨域请求中携带的请求头 如果客户端发送的请求头不在允许列表中,浏览器会拒绝该请求(触发 CORS 错误)。 默认允许的请求头有:

Origin, Content-Type, Accept, User-Agent, Cookie, Authorization,
X-Requested-With, X-Auth-Token, X-Token

func WithCORSAllowMethods

func WithCORSAllowMethods(methods ...string) cors.Option

WithCORSAllowMethods 设置允许的 Method 默认允许方法有:GET, POST, PUT, DELETE, OPTIONS

func WithCORSAllowOriginFunc

func WithCORSAllowOriginFunc(fun func(origin string) bool) cors.Option

WithCORSAllowOriginFunc 设置允许的源

func WithCORSExposeHeaders

func WithCORSExposeHeaders(keys ...string) cors.Option

WithCORSExposeHeaders 指定客户端 JavaScript 代码可以访问的响应头 如果需要访问自定义头,必须通过该方法声明。否则无法获取对应值 默认允许访问的响应头有:

Authorization, Content-MD5
Link, X-Pagination-Info, X-PaginateTotal-Count, X-More-Resource
X-Error-Code, X-Error-Data
X-Token

func WithCORSHeaders

func WithCORSHeaders(keys ...string) cors.Option

WithCORSHeaders 设置允许的请求头 该操作会同时进行 WithCORSAllowHeaders, WithCORSExposeHeaders 设置

func WithCORSMaxAge

func WithCORSMaxAge(d time.Duration) cors.Option

WithCORSMaxAge 指定预检请求(Preflight Request, OPTIONS)的缓存时间。默认为 12小时。 在缓存有效期内,浏览器不会对同一跨域请求重复发送预检请求,直接使用缓存结果。 设置合适的参数,可以优化高频跨域请求的性能(如 API 频繁调用)。 一般,24小时内,同一跨域请求(相同 URL 和方法)不需要再次发送 OPTIONS 预检请求。

func WithHttpCacheDebug

func WithHttpCacheDebug(enabled bool) httpcache.Option

WithHttpCacheDebug 是否启用 debug

func WithHttpCacheGlobalDuration

func WithHttpCacheGlobalDuration(d time.Duration) httpcache.Option

WithHttpCacheGlobalDuration 全局缓存有效时间

func WithHttpCacheGlobalHeaderKey

func WithHttpCacheGlobalHeaderKey(key string) httpcache.Option

WithHttpCacheGlobalHeaderKey 全局用于计算缓存的 Header

func WithHttpCacheGlobalHeaderKeys

func WithHttpCacheGlobalHeaderKeys(keys []string) httpcache.Option

WithHttpCacheGlobalHeaderKeys 全局用于计算缓存的 Header

func WithHttpCacheGlobalSkipFields

func WithHttpCacheGlobalSkipFields(field string, fields ...string) httpcache.Option

WithHttpCacheGlobalSkipFields 全局计算缓存的忽略字段

func WithHttpCacheJWTOption

func WithHttpCacheJWTOption(opt *jwt.Option) httpcache.Option

WithHttpCacheJWTOption jwt 鉴权参与缓存

func WithHttpCacheKeyPrefix

func WithHttpCacheKeyPrefix(str string) httpcache.Option

WithHttpCacheKeyPrefix 自定义缓存前缀

func WithHttpCacheLogger

func WithHttpCacheLogger(log xlog.XLogger) httpcache.Option

WithHttpCacheLogger 设置日志器

func WithHttpCacheRedisStore

func WithHttpCacheRedisStore(client *redis.Client) httpcache.Option

WithHttpCacheRedisStore 设置缓存存储器 redis 连接

func WithHttpCacheRedisStoreBy

func WithHttpCacheRedisStoreBy(addr string, db uint) httpcache.Option

WithHttpCacheRedisStoreBy 通过地址设置缓存存储器 redis 连接

func WithHttpCacheRoutePolicy

func WithHttpCacheRoutePolicy(route string, withToken bool, fields ...string) httpcache.Option

WithHttpCacheRoutePolicy 路由策略

func WithHttpCacheRouteRule

func WithHttpCacheRouteRule(route string, withToken bool, duration time.Duration, fields ...string) httpcache.Option

WithHttpCacheRouteRule 路由规则

func WithHttpCacheRouteSkipFiledPolicy

func WithHttpCacheRouteSkipFiledPolicy(route string, withToken bool, skipFields ...string) httpcache.Option

WithHttpCacheRouteSkipFiledPolicy 带忽略字段的路策略

func WithHttpCacheRouteSkipFiledRule

func WithHttpCacheRouteSkipFiledRule(route string, withToken bool, duration time.Duration, fields ...string) httpcache.Option

WithHttpCacheRouteSkipFiledRule 带忽略字段的路由规则

func WithRole

func WithRole(role httpcontext.IRole, roles ...httpcontext.IRole) gin.HandlerFunc

WithRole 角色权限中间件

func WithTrimSpaceEnabled

func WithTrimSpaceEnabled(enabled bool) mxss.Option

WithTrimSpaceEnabled 设置是否开启过滤前后空格

func WithXSSDebug

func WithXSSDebug(enabled bool) mxss.Option

WithXSSDebug 设置调试模式

func WithXSSGlobalFieldPolicy

func WithXSSGlobalFieldPolicy(p xss.Policy, fields ...string) mxss.Option

WithXSSGlobalFieldPolicy 指定全局字段过滤策略

func WithXSSGlobalPolicy

func WithXSSGlobalPolicy(p xss.Policy) mxss.Option

WithXSSGlobalPolicy 指定全局过滤策略

func WithXSSGlobalSkipFields

func WithXSSGlobalSkipFields(fields ...string) mxss.Option

WithXSSGlobalSkipFields 指定全局忽略字段 默认会自动跳过密码相关的字段,包括:

password, newPassword, oldPassword, confirmedPassword,
pwd, newPwd, oldPwd, confirmedPwd

func WithXSSRouteFieldPolicy

func WithXSSRouteFieldPolicy(routeRule string, policy xss.Policy, fields ...string) mxss.Option

WithXSSRouteFieldPolicy 指定路由的字段策略 routeRule 路由规则,如果路由包含该字符串则匹配成功

func WithXSSRoutePolicy

func WithXSSRoutePolicy(routeRule string, policy xss.Policy, skipFields ...string) mxss.Option

WithXSSRoutePolicy 指定路由策略 routeRule 路由规则,如果路由包含该字符串则匹配成功

func WithoutHttpCacheResponseHeader

func WithoutHttpCacheResponseHeader(without bool) httpcache.Option

WithoutHttpCacheResponseHeader 是否不缓存响应 header。默认是(即:不缓存)

func XSSFilter

func XSSFilter(opts ...mxss.Option) gin.HandlerFunc

XSSFilter XSS 过滤

usage:

r.Use(middleware.XSSFilter(
	//middleware.XSSDebug(),
	middleware.WithXSSGlobalPolicy(xss.PolicyStrict),
	middleware.WithXSSGlobalFieldPolicy(xss.PolicyUGC, "content", "details"),
	middleware.WithXSSGlobalSkipFields("password"),
	middleware.WithXSSRoutePolicy("admin", xss.PolicyUGC),
	middleware.WithXSSRoutePolicy("/callback/", xss.PolicyNone),
	middleware.WithXSSRoutePolicy("/endpoint", xss.PolicyNone),
	middleware.WithXSSRoutePolicy("/ping", xss.PolicyNone),
	middleware.WithXSSRouteFieldPolicy("/user/", xss.PolicyUGC, "content"),
))

Types

type HttpLoggerOption

type HttpLoggerOption struct {
	Logger    xlog.XLog
	OnlyError bool // 仅发生错误时,打印日志;否则,打印所有请求
}

type IgnorePath

type IgnorePath struct {
	Path   string
	Method string
}

type SessionOption

type SessionOption struct {
	Path     string
	Domain   string
	MaxAge   time.Duration
	Secure   bool
	HttpOnly bool
	SameSite http.SameSite
}

Directories

Path Synopsis
internal
jwt
xss

Jump to

Keyboard shortcuts

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