upgrade: 支持初始化上下文数据中间件 + 支持自动启用请求初始化中间件
This commit is contained in:
@ -31,7 +31,28 @@ type serverOption struct {
|
||||
serverList []*apiDocDefine.ServerItem // 服务器环境列表
|
||||
enablePprof bool // 启用pprof
|
||||
enableCors bool // 启动跨域支持
|
||||
disableInitRequest bool // 禁用初始化请求
|
||||
loggerCfg *middleware.AccessConfig // 日志配置
|
||||
initContextData gin.HandlerFunc // 初始化一些请求数据
|
||||
}
|
||||
|
||||
// WithEnableInitRequest 启用pprof
|
||||
func WithEnableInitRequest(disable bool) SetServerOptionFunc {
|
||||
return func(so *serverOption) {
|
||||
so.disableInitRequest = disable
|
||||
}
|
||||
}
|
||||
|
||||
// WithInitContextData 初始化一些请求数据
|
||||
func WithInitContextData(data map[string]any) SetServerOptionFunc {
|
||||
return func(so *serverOption) {
|
||||
f := func(ctx *gin.Context) {
|
||||
for k, v := range data {
|
||||
ctx.Set(k, v)
|
||||
}
|
||||
}
|
||||
so.initContextData = f
|
||||
}
|
||||
}
|
||||
|
||||
// WithSwaggerUITheme 设置swaggerUI主题
|
||||
|
@ -9,10 +9,11 @@ package router
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"git.zhangdeman.cn/zhangdeman/graceful"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.zhangdeman.cn/zhangdeman/graceful"
|
||||
|
||||
"git.zhangdeman.cn/zhangdeman/gin/define"
|
||||
|
||||
apiDoc "git.zhangdeman.cn/gateway/api-doc"
|
||||
@ -74,6 +75,12 @@ func NewServer(port int, optionList ...SetServerOptionFunc) *server {
|
||||
}
|
||||
option := newServerOption(port, optionList...)
|
||||
globalMiddlewareList := make([]gin.HandlerFunc, 0)
|
||||
if nil != option.initContextData {
|
||||
globalMiddlewareList = append(globalMiddlewareList, option.initContextData) // 初始化一些全局的变量
|
||||
}
|
||||
if !option.disableInitRequest { // 启用了初始化请求
|
||||
globalMiddlewareList = append(globalMiddlewareList, middleware.InitRequest()) // 初始化请求
|
||||
}
|
||||
// CustomContext 必须在第一个, 并且进行初始化
|
||||
globalMiddlewareList = append(
|
||||
globalMiddlewareList,
|
||||
|
Reference in New Issue
Block a user