优化升级gin框架的二次包装 #19

Merged
zhangdeman merged 12 commits from feature/upgrade_gin into master 2025-12-29 10:40:06 +08:00
9 changed files with 21 additions and 25 deletions
Showing only changes of commit 1636a2652f - Show all commits

2
go.mod
View File

@@ -6,7 +6,7 @@ toolchain go1.24.2
require ( require (
git.zhangdeman.cn/zhangdeman/api-doc v1.0.3-0.20251013152001-868ee8955623 git.zhangdeman.cn/zhangdeman/api-doc v1.0.3-0.20251013152001-868ee8955623
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20251217031322-9e8b61fd5156 git.zhangdeman.cn/zhangdeman/consts v0.0.0-20251226040044-6bc8da22219a
git.zhangdeman.cn/zhangdeman/dynamic-struct v0.0.0-20251013092857-dcf591d4e8a8 git.zhangdeman.cn/zhangdeman/dynamic-struct v0.0.0-20251013092857-dcf591d4e8a8
git.zhangdeman.cn/zhangdeman/exception v0.0.0-20250510123912-a0d52fc093ab git.zhangdeman.cn/zhangdeman/exception v0.0.0-20250510123912-a0d52fc093ab
git.zhangdeman.cn/zhangdeman/graceful v0.0.0-20250529070945-92833db6f3a4 git.zhangdeman.cn/zhangdeman/graceful v0.0.0-20250529070945-92833db6f3a4

2
go.sum
View File

@@ -6,6 +6,8 @@ git.zhangdeman.cn/zhangdeman/consts v0.0.0-20251101092813-3dd9fb807f1c h1:H0Tlh7
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20251101092813-3dd9fb807f1c/go.mod h1:5p8CEKGBxi7qPtTXDI3HDmqKAfIm5i/aBWdrbkbdNjc= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20251101092813-3dd9fb807f1c/go.mod h1:5p8CEKGBxi7qPtTXDI3HDmqKAfIm5i/aBWdrbkbdNjc=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20251217031322-9e8b61fd5156 h1:VaaejWXKShnuySe0o2twIBMkWc8bJ+Fw654KLKjoXW8= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20251217031322-9e8b61fd5156 h1:VaaejWXKShnuySe0o2twIBMkWc8bJ+Fw654KLKjoXW8=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20251217031322-9e8b61fd5156/go.mod h1:5p8CEKGBxi7qPtTXDI3HDmqKAfIm5i/aBWdrbkbdNjc= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20251217031322-9e8b61fd5156/go.mod h1:5p8CEKGBxi7qPtTXDI3HDmqKAfIm5i/aBWdrbkbdNjc=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20251226040044-6bc8da22219a h1:p85je5ExTyUsd2jR+Lq2rSJneAPM3MkuUhFHH+TfhEM=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20251226040044-6bc8da22219a/go.mod h1:5p8CEKGBxi7qPtTXDI3HDmqKAfIm5i/aBWdrbkbdNjc=
git.zhangdeman.cn/zhangdeman/dynamic-struct v0.0.0-20251013092857-dcf591d4e8a8 h1:Pw981jG3hH9ZHrB3s1xPpsZafgX3USuMAjnGi2GEP9Y= git.zhangdeman.cn/zhangdeman/dynamic-struct v0.0.0-20251013092857-dcf591d4e8a8 h1:Pw981jG3hH9ZHrB3s1xPpsZafgX3USuMAjnGi2GEP9Y=
git.zhangdeman.cn/zhangdeman/dynamic-struct v0.0.0-20251013092857-dcf591d4e8a8/go.mod h1:xtCw3om5DRrG30EfQd/lfQPXgptfK7l9oBSt4Kdhjok= git.zhangdeman.cn/zhangdeman/dynamic-struct v0.0.0-20251013092857-dcf591d4e8a8/go.mod h1:xtCw3om5DRrG30EfQd/lfQPXgptfK7l9oBSt4Kdhjok=
git.zhangdeman.cn/zhangdeman/easylock v0.0.0-20230731062340-983985c12eda h1:bMD6r9gjRy7cO+T4zRQVYAesgIblBdTnhzT1vN5wjvI= git.zhangdeman.cn/zhangdeman/easylock v0.0.0-20230731062340-983985c12eda h1:bMD6r9gjRy7cO+T4zRQVYAesgIblBdTnhzT1vN5wjvI=

View File

@@ -24,7 +24,7 @@ func init() {
cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
logger, err := cfg.Build() logger, err := cfg.Build()
if err != nil { if err != nil {
panic("init logger error") panic("init logger error: " + err.Error())
} }
Instance = logger.Sugar().Desugar() Instance = logger.Sugar().Desugar()
} }

View File

@@ -32,7 +32,7 @@ func HookAfterResponseMiddleware(hookFunc HookFunc) gin.HandlerFunc {
ctx, ctx,
[]byte(ctx.GetString(handleConfig.RecordRequestDataField)), []byte(ctx.GetString(handleConfig.RecordRequestDataField)),
ctx.GetStringMap(handleConfig.RecordResponseDataField), ctx.GetStringMap(handleConfig.RecordResponseDataField),
request.WrapperHandle.GetCtxIntData(ctx, handleConfig.StartRequestTimeField, 0)-request.WrapperHandle.GetCtxIntData(ctx, handleConfig.StartRequestTimeField, 0), request.WrapperHandle.GetCtxIntData(ctx, handleConfig.FinishRequestTimeField, 0)-request.WrapperHandle.GetCtxIntData(ctx, handleConfig.StartRequestTimeField, 0),
) )
} }
} }

View File

@@ -10,11 +10,13 @@ package request
import ( import (
"bytes" "bytes"
"errors" "errors"
"github.com/mcuadros/go-defaults"
"io" "io"
"net/http" "net/http"
"strings" "strings"
"git.zhangdeman.cn/zhangdeman/wrapper/op_array"
"github.com/mcuadros/go-defaults"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"git.zhangdeman.cn/zhangdeman/gin/define" "git.zhangdeman.cn/zhangdeman/gin/define"
@@ -44,11 +46,9 @@ func (f *form) Parse(ctx *gin.Context, receiver interface{}) error {
// 因为请求体被读一遍之后就没了,重新赋值 requestBody // 因为请求体被读一遍之后就没了,重新赋值 requestBody
ctx.Request.Body = io.NopCloser(bytes.NewReader(requestBody)) ctx.Request.Body = io.NopCloser(bytes.NewReader(requestBody))
method := strings.ToUpper(ctx.Request.Method) method := strings.ToUpper(ctx.Request.Method)
if method == http.MethodGet || if op_array.ArrayType([]string{
method == http.MethodPatch || http.MethodGet, http.MethodPatch, http.MethodTrace, http.MethodConnect, http.MethodOptions,
method == http.MethodTrace || }).Has(method) >= 0 {
method == http.MethodConnect ||
method == http.MethodOptions {
if err := ctx.ShouldBindQuery(receiver); nil != err { if err := ctx.ShouldBindQuery(receiver); nil != err {
return err return err
} }

View File

@@ -81,8 +81,6 @@ func (c controller) methodConfig(reflectMethod reflect.Method) (cfg UriConfig, n
return return
} }
cfg.ResultDataType = methodType.Out(0) cfg.ResultDataType = methodType.Out(0)
if cfg.ResultDataType == nil {
}
if methodType.Out(1).Kind().String() != ErrorType { if methodType.Out(1).Kind().String() != ErrorType {
// 判断是否是实现 error接口的方法 // 判断是否是实现 error接口的方法
outputErrParse := false outputErrParse := false
@@ -106,7 +104,6 @@ func (c controller) methodConfig(reflectMethod reflect.Method) (cfg UriConfig, n
// 开启输出严格模式校验 // 开启输出严格模式校验
if methodType.Out(0).Kind() != reflect.Struct && methodType.Out(0).Kind() != reflect.Map { if methodType.Out(0).Kind() != reflect.Struct && methodType.Out(0).Kind() != reflect.Map {
panic(cfg.Path + " : 接口配置输出严格校验, 输出数据类型必须为 struct 或 *struct 或 map, 实际返回数据类型 : " + methodType.Out(0).Kind().String()) panic(cfg.Path + " : 接口配置输出严格校验, 输出数据类型必须为 struct 或 *struct 或 map, 实际返回数据类型 : " + methodType.Out(0).Kind().String())
return
} }
} }

View File

@@ -115,6 +115,5 @@ func (s *server) RequestHandler(uriCfg UriConfig) gin.HandlerFunc {
response.SendWithException(ctx, e, &define.ResponseOption{ response.SendWithException(ctx, e, &define.ResponseOption{
ContentType: consts.MimeTypeJson, ContentType: consts.MimeTypeJson,
}) })
return
} }
} }

View File

@@ -18,19 +18,23 @@ import (
// hook 执行hook逻辑 // hook 执行hook逻辑
func (s *server) hook(ctx *gin.Context, uriCfg UriConfig) { func (s *server) hook(ctx *gin.Context, uriCfg UriConfig) {
responseAfter, exist := ctx.Get(consts.GinLogicAfterResponseKey) var (
exists bool
isSuccess any
responseAfter any
)
innerContext := util.GinCtxToContext(ctx) innerContext := util.GinCtxToContext(ctx)
if !exist || nil != responseAfter { if responseAfter, exists = ctx.Get(consts.GinLogicAfterResponseKey); !exists || nil != responseAfter {
// 未配置 // 未配置
logger.Instance.Debug("未配置Logic执行后的hook逻辑", pkgLogger.NewLogData(innerContext, logger.RecordType, logger.CodeLogicHook, map[string]any{ logger.Instance.Debug("未配置 Logic 执行后的 hook 逻辑", pkgLogger.NewLogData(innerContext, logger.RecordType, logger.CodeLogicHook, map[string]any{
"uri": uriCfg.Path, "uri": uriCfg.Path,
"logic_after_response_key": consts.GinLogicAfterResponseKey, "logic_after_response_key": consts.GinLogicAfterResponseKey,
}).ToFieldList()...) }).ToFieldList()...)
return return
} }
isSuccess, exist := ctx.Get(consts.GinRequestSuccess)
success := false success := false
if nil != isSuccess && (isSuccess == "1" || isSuccess == "true" || isSuccess.(bool)) { if isSuccess, exists = ctx.Get(consts.GinRequestSuccess); exists && nil != isSuccess && (isSuccess == "1" || isSuccess == "true" || isSuccess.(bool)) {
success = true success = true
} }
hookInstance := responseAfter.(*define.LogicAfterResponse) hookInstance := responseAfter.(*define.LogicAfterResponse)
@@ -47,14 +51,12 @@ func (s *server) hookAfter(ctx *gin.Context, uriCfg UriConfig, hookInstance *def
innerContext := util.GinCtxToContext(ctx) innerContext := util.GinCtxToContext(ctx)
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
logger.Instance.Error("hook执行异常", pkgLogger.NewLogData(innerContext, logger.RecordType, logger.CodeLogicHook, map[string]any{ logger.Instance.Error("hook 执行异常", pkgLogger.NewLogData(innerContext, logger.RecordType, logger.CodeLogicHook, map[string]any{
"uri": uriCfg.Path, "uri": uriCfg.Path,
"logic_after_response_key": consts.GinLogicAfterResponseKey, "logic_after_response_key": consts.GinLogicAfterResponseKey,
"error": err.(error).Error(), "error": err.(error).Error(),
"logic_success": success, "logic_success": success,
}).ToFieldList()...) }).ToFieldList()...)
} else {
} }
}() }()
if success { if success {

View File

@@ -77,10 +77,6 @@ func NewServer(port int, optionList ...SetServerOptionFunc) *server {
if !option.disableInitRequest { // 启用了初始化请求 if !option.disableInitRequest { // 启用了初始化请求
globalMiddlewareList = append(globalMiddlewareList, middleware.InitRequest()) // 初始化请求 globalMiddlewareList = append(globalMiddlewareList, middleware.InitRequest()) // 初始化请求
} }
// CustomContext 必须在第一个, 并且进行初始化
globalMiddlewareList = append(
globalMiddlewareList,
)
if nil != option.loggerCfg { if nil != option.loggerCfg {
// 请求日志记录中间件 // 请求日志记录中间件
globalMiddlewareList = append(globalMiddlewareList, middleware.LogRequest(option.loggerCfg)) globalMiddlewareList = append(globalMiddlewareList, middleware.LogRequest(option.loggerCfg))