From f3437dc00fd21e07c1a5b0a4d64728f0bad3d5d9 Mon Sep 17 00:00:00 2001 From: John Guo Date: Wed, 2 Aug 2023 20:35:58 +0800 Subject: [PATCH] add generic support for http routes registering #2227 #2457 (#2807) --- net/ghttp/ghttp_server_service_handler.go | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/net/ghttp/ghttp_server_service_handler.go b/net/ghttp/ghttp_server_service_handler.go index 8422654a3..90a2deebd 100644 --- a/net/ghttp/ghttp_server_service_handler.go +++ b/net/ghttp/ghttp_server_service_handler.go @@ -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] +}