From 88bdeb854a889ee19e6bb4b6ccbed1c7a1d8df2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Sun, 17 Aug 2025 14:05:17 +0800 Subject: [PATCH] =?UTF-8?q?upgrade:=20=E6=94=AF=E6=8C=81=E5=88=9D=E5=A7=8B?= =?UTF-8?q?=E5=8C=96=E4=B8=8A=E4=B8=8B=E6=96=87=E6=95=B0=E6=8D=AE=E4=B8=AD?= =?UTF-8?q?=E9=97=B4=E4=BB=B6=20+=20=E6=94=AF=E6=8C=81=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E5=90=AF=E7=94=A8=E8=AF=B7=E6=B1=82=E5=88=9D=E5=A7=8B=E5=8C=96?= =?UTF-8?q?=E4=B8=AD=E9=97=B4=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- router/option.go | 21 +++++++++++++++++++++ router/server.go | 9 ++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/router/option.go b/router/option.go index babf1af..ebb42df 100644 --- a/router/option.go +++ b/router/option.go @@ -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主题 diff --git a/router/server.go b/router/server.go index 98d524b..e6ad6c7 100644 --- a/router/server.go +++ b/router/server.go @@ -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,