From 303f21646655dcce7a83516b0c0523b0f4cc6e94 Mon Sep 17 00:00:00 2001 From: fgy Date: Fri, 18 Oct 2024 18:21:38 +0800 Subject: [PATCH] optimzie: handler path is for package --- cmd/hz/protobuf/ast.go | 3 +++ cmd/hz/thrift/ast.go | 4 ++++ cmd/hz/util/string.go | 7 +++++++ 3 files changed, 14 insertions(+) diff --git a/cmd/hz/protobuf/ast.go b/cmd/hz/protobuf/ast.go index 3ccfc9b51..1ea0316b6 100644 --- a/cmd/hz/protobuf/ast.go +++ b/cmd/hz/protobuf/ast.go @@ -156,6 +156,9 @@ func astToService(ast *descriptorpb.FileDescriptorProto, resolver *Resolver, cmd if !ok || len(handlerOutDir) == 0 { handlerOutDir = "" } + if !util.IsValidPackageName(filepath.Base(handlerOutDir)) { + handlerOutDir = "" + } if len(handlerOutDir) == 0 { handlerOutDir = servicePath } diff --git a/cmd/hz/thrift/ast.go b/cmd/hz/thrift/ast.go index 83b27fd7f..d0af96894 100644 --- a/cmd/hz/thrift/ast.go +++ b/cmd/hz/thrift/ast.go @@ -18,6 +18,7 @@ package thrift import ( "fmt" + "path/filepath" "sort" "strings" @@ -125,6 +126,9 @@ func astToService(ast *parser.Thrift, resolver *Resolver, args *config.Argument) } else if len(genPaths) > 0 { return nil, fmt.Errorf("too many 'api.handler_path' for %s", m.Name) } + if !util.IsValidPackageName(filepath.Base(handlerOutDir)) { + handlerOutDir = "" + } hmethod, path := httpAnnos[0].method, httpAnnos[0].path if len(path) == 0 || path[0] == "" { diff --git a/cmd/hz/util/string.go b/cmd/hz/util/string.go index c31775311..bf325d1b9 100644 --- a/cmd/hz/util/string.go +++ b/cmd/hz/util/string.go @@ -18,6 +18,7 @@ package util import ( "reflect" + "regexp" "strings" "unicode/utf8" "unsafe" @@ -97,3 +98,9 @@ func SnakeString(s string) string { } return strings.ToLower(Bytes2Str(data)) } + +func IsValidPackageName(name string) bool { + // Regular expression for a valid package name + re := regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_]*$`) + return re.MatchString(name) +}