Explorar o código

feat(transport): 添加路径生成器以自定义HTTP路由路径

- 新增 `PathGeneratorFunc` 类 `defaultPathGenerator`
- 添加 `SetPathGeneratorFunc` 方法用于设置自定义路径生成逻辑
- 修改 `RegisterRoute` 函数,移除 baseUrl 参数,统一使用根路径注册
- 在路由注册时调用 `pathGenerator` 生成具体路径
- 增加对 `SetReplyFunc` 和 `SetPathGeneratorFunc` 空函数指针检查
lihf hai 3 días
pai
achega
64316a3c2e

+ 22 - 0
transport/http/handler/path.go

@@ -0,0 +1,22 @@
+package handler
+
+import "fmt"
+
+type PathGeneratorFunc func(serviceName, methodName string) string
+
+var pathGeneratorFunc PathGeneratorFunc = defaultPathGenerator
+
+func pathGenerator(serviceName, methodName string) string {
+	return pathGeneratorFunc(serviceName, methodName)
+}
+
+func defaultPathGenerator(serviceName, methodName string) string {
+	return fmt.Sprintf("/api/%s/%s", serviceName, methodName)
+}
+
+func SetPathGeneratorFunc(f PathGeneratorFunc) {
+	if f == nil {
+		panic("pathGeneratorFunc is nil")
+	}
+	pathGeneratorFunc = f
+}

+ 3 - 6
transport/http/handler/route.go

@@ -16,11 +16,8 @@ import (
 	"google.golang.org/protobuf/proto"
 )
 
-func RegisterRoute(s *http.Server, srv any, svcDesc grpc.ServiceDesc, baseUrl string) {
-	r := s.Route("/api/")
-	if baseUrl != "" {
-		r = s.Route(baseUrl)
-	}
+func RegisterRoute(s *http.Server, srv any, svcDesc grpc.ServiceDesc) {
+	r := s.Route("/")
 
 	// 加载完整的服务描述符
 	fullSvcDesc, err := grpcreflect.LoadServiceDescriptor(&svcDesc)
@@ -117,7 +114,7 @@ func GetOptionByServiceDescriptor(sd *desc.ServiceDescriptor, serviceName, metho
 		}
 	}
 	if option.Path == "" {
-		option.Path = fmt.Sprintf("/%s/%s", serviceName, methodName)
+		option.Path = pathGenerator(serviceName, methodName)
 	}
 	if option.Method == "" {
 		option.Method = http2.MethodPost

+ 3 - 0
transport/http/reply/reply.go

@@ -26,5 +26,8 @@ func WrapReply(data any) any {
 }
 
 func SetReplyFunc(f ReplyFunc) {
+	if f == nil {
+		panic("reply: SetReplyFunc: f is nil")
+	}
 	wrapReplyFunc = f
 }