包装handler支持响应后触发相关逻辑

This commit is contained in:
2025-02-28 16:48:22 +08:00
parent 3432087fbd
commit b95d464c89
2 changed files with 53 additions and 10 deletions

View File

@ -13,6 +13,7 @@ import (
"git.zhangdeman.cn/zhangdeman/gin/response"
"github.com/gin-gonic/gin"
"reflect"
"sync"
)
// RequestHandler 获取请求处理方法
@ -45,6 +46,15 @@ func RequestHandler(uriCfg UriConfig) gin.HandlerFunc {
return
}
// 初始化响应之后logic
logicAfterResponse := &LogicAfterResponse{
SuccessHookFuncList: make([]func(), 0),
FailureHookFuncList: make([]func(), 0),
Lock: &sync.RWMutex{},
}
// 此处暴露出去,是为了使用方可以获取到对应数据
ctx.Set(LogicAfterResponseKey, logicAfterResponse)
// 执行逻辑
inputValue := reflect.ValueOf(formValue)
if uriCfg.FormDataType.Kind() != reflect.Ptr {
@ -54,22 +64,31 @@ func RequestHandler(uriCfg UriConfig) gin.HandlerFunc {
if resList[1].IsNil() {
// 请求成功
response.Success(ctx, resList[0].Interface())
// 执行成功之后的逻辑
for _, item := range logicAfterResponse.SuccessHookFuncList {
if item != nil {
item()
}
}
return
}
// 请求失败
if e, ok = resList[1].Interface().(exception.IException); ok {
response.SendWithException(ctx, e, nil)
return
}
if err, ok = resList[1].Interface().(error); ok {
// 本身就是exception.IException
} else if err, ok = resList[1].Interface().(error); ok {
e = exception.NewFromError(-1, err)
response.SendWithException(ctx, e, nil)
return
} else {
e = exception.NewWithCodeAndData(-1, map[string]any{
"err": resList[1].Interface(),
})
}
e = exception.NewWithCodeAndData(-1, map[string]any{
"err": resList[1].Interface(),
})
response.SendWithException(ctx, e, nil)
// 执行失败之后的逻辑
for _, item := range logicAfterResponse.FailureHookFuncList {
if item != nil {
item()
}
}
return
}
}