diff --git a/cmd/kratos/internal/server/server.go b/cmd/kratos/internal/server/server.go index 4f1947c5b4d769f26ef362ad978efc9a4b9bfb44..e5bea59ec5d8716c2f06d6a03508111dc094241b 100644 --- a/cmd/kratos/internal/server/server.go +++ b/cmd/kratos/internal/server/server.go @@ -10,6 +10,7 @@ import ( "github.com/emicklei/proto" "github.com/spf13/cobra" + "golang.org/x/mod/modfile" ) // CmdServer the service command. @@ -45,11 +46,8 @@ func run(cmd *cobra.Command, args []string) { fmt.Fprintln(os.Stderr, "walkDir error, err is:", err) return } - - abs, err := filepath.Abs(args[0]) - parentDir := filepath.Dir(filepath.Dir(abs)) - var res Services + res.Modname = modName() for _, filename := range files { addProtoServer(filename) reader, err := os.Open(filename) @@ -63,9 +61,7 @@ func run(cmd *cobra.Command, args []string) { if err != nil { log.Fatal(err) } - - abs, err = filepath.Abs(filepath.Dir(filename)) - targetPath, _ := filepath.Rel(parentDir, abs) + targetPath := filepath.Join(res.Modname, filepath.Dir(filename)) proto.Walk(definition, proto.WithService(func(s *proto.Service) { cs := Service{ @@ -97,7 +93,7 @@ func run(cmd *cobra.Command, args []string) { log.Fatal(err) } - abs, err = filepath.Abs(filepath.Join(targetDir, "grpc.go")) + abs, _ := filepath.Abs(filepath.Join(targetDir, "grpc.go")) fmt.Println("wrote " + abs) to = filepath.Join(targetDir, "http_mdf.go") @@ -113,7 +109,7 @@ func run(cmd *cobra.Command, args []string) { if err != nil { log.Fatal(err) } - abs, err = filepath.Abs(filepath.Join(targetDir, "http.go")) + abs, _ = filepath.Abs(filepath.Join(targetDir, "http.go")) fmt.Println("wrote " + abs) } @@ -135,3 +131,11 @@ func WalkDir(dirPth, suffix string) (files []string, err error) { return files, err } + +func modName() string { + modBytes, err := os.ReadFile("go.mod") + if err != nil { + return "" + } + return modfile.ModulePath(modBytes) +} diff --git a/cmd/kratos/internal/server/template.go b/cmd/kratos/internal/server/template.go index 832c7b0b8375b7be1f08d7cd22b56655430532c7..5cf6d9803fb67a53f31a08d0f4fc028a82d41ca4 100644 --- a/cmd/kratos/internal/server/template.go +++ b/cmd/kratos/internal/server/template.go @@ -13,6 +13,7 @@ type Service struct { type Services struct { Services []Service + Modname string } var grpcServiceTemplate = ` @@ -24,8 +25,9 @@ import ( {{- range $element := .Services}} s{{$element.NameLower}} "{{$element.ImportPath}}" {{- end}} + "{{.Modname}}/internal/conf" + "{{.Modname}}/internal/service" "github.com/go-kratos/kratos/v2/log" - "github.com/go-kratos/kratos/v2/middleware/recovery" "github.com/go-kratos/kratos/v2/transport/grpc" ) @@ -74,8 +76,9 @@ import ( {{- range $element := .Services}} s{{$element.NameLower}} "{{$element.ImportPath}}" {{- end}} + "{{.Modname}}/internal/conf" + "{{.Modname}}/internal/service" "github.com/go-kratos/kratos/v2/log" - "github.com/go-kratos/kratos/v2/middleware/recovery" "github.com/go-kratos/kratos/v2/transport/http" )