add generic support for http routes registering #2227 #2457 (#2807)

This commit is contained in:
John Guo
2023-08-02 20:35:58 +08:00
committed by GitHub
parent 574d63b4fd
commit f3437dc00f

View File

@ -184,21 +184,23 @@ func (s *Server) checkAndCreateFuncInfo(f interface{}, pkgPath, structName, meth
}
// The request struct should be named as `xxxReq`.
if !gstr.HasSuffix(reflectType.In(1).String(), `Req`) {
reqStructName := trimGeneric(reflectType.In(1).String())
if !gstr.HasSuffix(reqStructName, `Req`) {
err = gerror.NewCodef(
gcode.CodeInvalidParameter,
`invalid struct naming for request: defined as "%s", but it should be named with "Req" suffix like "XxxReq"`,
reflectType.In(1).String(),
reqStructName,
)
return
}
// The response struct should be named as `xxxRes`.
if !gstr.HasSuffix(reflectType.Out(0).String(), `Res`) {
resStructName := trimGeneric(reflectType.Out(0).String())
if !gstr.HasSuffix(resStructName, `Res`) {
err = gerror.NewCodef(
gcode.CodeInvalidParameter,
`invalid struct naming for response: defined as "%s", but it should be named with "Res" suffix like "XxxRes"`,
reflectType.Out(0).String(),
resStructName,
)
return
}
@ -208,3 +210,14 @@ func (s *Server) checkAndCreateFuncInfo(f interface{}, pkgPath, structName, meth
info.Value = reflect.ValueOf(f)
return
}
func trimGeneric(structName string) string {
var (
leftBraceIndex = strings.Index(structName, "[")
rightBraceIndex = strings.Index(structName, "]")
)
if leftBraceIndex == -1 || rightBraceIndex == -1 {
return structName
}
return structName[:leftBraceIndex]
}