返回数据支持是否严格模式的校验, 严格模式下, 必须返回结构体或者map

This commit is contained in:
2025-02-07 17:19:25 +08:00
parent e95061a1a8
commit 1b1964881f
6 changed files with 35 additions and 23 deletions

View File

@ -8,7 +8,6 @@
package router
import (
"fmt"
"reflect"
"strings"
)
@ -83,7 +82,7 @@ func (c controller) methodConfig(reflectMethod reflect.Method) (cfg UriConfig, n
return
}
// 第一个参数必须是 *gin.Context
if methodType.In(1).String() != "*gin.Context" {
if methodType.In(1).String() != GinContextType {
needRegister = false
return
}
@ -100,22 +99,28 @@ func (c controller) methodConfig(reflectMethod reflect.Method) (cfg UriConfig, n
}
// 解析第一个返回值, 要求必须是结构体或者是map
/*if methodType.Out(0).Kind() != reflect.Struct && methodType.Out(0).Kind() != reflect.Map {
needRegister = false
return
}*/
if methodType.Out(1).Kind().String() != "error" {
outputStrictModel := metaField.Tag.Get(TagNameOutputStrict)
// 输出是否严格模式
cfg.OutputStrict = outputStrictModel == "1" || outputStrictModel == "true"
if cfg.OutputStrict {
// 开启输出严格模式校验
if methodType.Out(0).Kind() != reflect.Struct && methodType.Out(0).Kind() != reflect.Map {
needRegister = false
return
}
}
if methodType.Out(1).Kind().String() != ErrorType {
// 判断是否是实现 error接口的方法
outputErrParse := false
for j := 0; j < methodType.Out(1).NumMethod(); j++ {
if methodType.Out(1).Method(j).Name == "Error" && // 实现Error方法
if methodType.Out(1).Method(j).Name == ErrorInterfaceFuncName && // 实现Error方法
methodType.Out(1).Method(j).Type.NumIn() == 0 && // 没有任何参数
methodType.Out(1).Method(j).Type.NumOut() == 1 && // 一个返回值
methodType.Out(1).Method(j).Type.Out(0).Kind().String() == reflect.String.String() {
outputErrParse = true
break
}
fmt.Println(methodType.Out(1).Method(j).Name, methodType.Out(1).Method(j).Type.NumIn(), methodType.Out(1).Method(j).Type.NumOut(), methodType.Out(1).Method(j).Type.Out(0).Kind().String())
}
if !outputErrParse {
needRegister = false