diff --git a/goutils/proto_build/main.go b/goutils/proto_build/main.go index a5d52fd..86f87fb 100644 --- a/goutils/proto_build/main.go +++ b/goutils/proto_build/main.go @@ -267,6 +267,12 @@ func ExecCreateAutoLogic(workerSpaceDir string, ServiceName string, genDir, pack // 处理main.go文件 defer func() { // name := underscoreToLowerCamelCase(ServiceName) + + // name := underscoreToLowerCamelCase(ServiceName) + createFile("server/main_gen.go", func(f io.Writer) error { + return tpl.ExecuteTemplate(f, "main_gen.tpl", mtpl) + }) + createFileWithPermNotExists("server/main.go", func(f io.Writer) error { return tpl.ExecuteTemplate(f, "main.tpl", mtpl) }) @@ -1246,6 +1252,34 @@ func _getTypeString(expr ast.Expr, packageName *string, level int) string { } } +func createFile(filename string, do func(f io.Writer) error) error { + // 检测文件是否存在 + + file, err := os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644) + if err != nil { + return err + } + defer file.Close() + + var buf = bytes.NewBuffer(nil) + err = do(buf) + if err != nil { + panic(err) + } + data, err := format.Source(buf.Bytes()) + if err != nil { + _, err = file.Write(buf.Bytes()) + } else { + _, err = file.Write(data) + } + + if err != nil { + panic(err) + } + + return nil +} + func createFileWithPermNotExists(filename string, do func(f io.Writer) error) error { // 检测文件是否存在 _, err := os.Stat(filename) diff --git a/goutils/proto_build/tpls/main.tpl b/goutils/proto_build/tpls/main.tpl index 4d41cf4..e97338e 100644 --- a/goutils/proto_build/tpls/main.tpl +++ b/goutils/proto_build/tpls/main.tpl @@ -30,9 +30,8 @@ func main() { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer(sopt) //新建一个grpc服务 - {{range .StructServiceNames}} - service.Register{{.StructServiceName}}Server(s, &{{.LogicPackageName}}.{{.StructServiceName}}LogicGrpc{}) // {{.LogicPackageName}} 服务注册 - {{- end}} + + MainRegisterServer(s) // 注册所有的service if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/goutils/proto_build/tpls/main_gen.tpl b/goutils/proto_build/tpls/main_gen.tpl new file mode 100644 index 0000000..4809b22 --- /dev/null +++ b/goutils/proto_build/tpls/main_gen.tpl @@ -0,0 +1,15 @@ +package main + +import ( + "{{.ProjectName}}/gen/go/service" + "{{.ProjectName}}/server/logics/info_logic" + "{{.ProjectName}}/server/logics/product_logic" + + "google.golang.org/grpc" +) + +func MainRegisterServer(s *grpc.Server) { + {{range .StructServiceNames}} + service.Register{{.StructServiceName}}Server(s, &{{.LogicPackageName}}.{{.StructServiceName}}LogicGrpc{}) // {{.LogicPackageName}} 服务注册 + {{- end}} +}