genmain.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package generator
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "strings"
  6. conf "github.com/tal-tech/go-zero/tools/goctl/config"
  7. "github.com/tal-tech/go-zero/tools/goctl/rpc/parser"
  8. "github.com/tal-tech/go-zero/tools/goctl/util"
  9. "github.com/tal-tech/go-zero/tools/goctl/util/format"
  10. "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
  11. )
  12. const mainTemplate = `package main
  13. import (
  14. "flag"
  15. "fmt"
  16. {{.imports}}
  17. "github.com/tal-tech/go-zero/core/conf"
  18. "github.com/tal-tech/go-zero/core/service"
  19. "github.com/tal-tech/go-zero/zrpc"
  20. "google.golang.org/grpc"
  21. "google.golang.org/grpc/reflection"
  22. )
  23. var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file")
  24. func main() {
  25. flag.Parse()
  26. var c config.Config
  27. conf.MustLoad(*configFile, &c)
  28. ctx := svc.NewServiceContext(c)
  29. srv := server.New{{.serviceNew}}Server(ctx)
  30. s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
  31. {{.pkg}}.Register{{.service}}Server(grpcServer, srv)
  32. switch c.Mode {
  33. case service.DevMode,service.TestMode:
  34. reflection.Register(grpcServer)
  35. default:
  36. }
  37. })
  38. defer s.Stop()
  39. fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
  40. s.Start()
  41. }
  42. `
  43. // GenMain generates the main file of the rpc service, which is an rpc service program call entry
  44. func (g *DefaultGenerator) GenMain(ctx DirContext, proto parser.Proto, cfg *conf.Config) error {
  45. mainFilename, err := format.FileNamingFormat(cfg.NamingFormat, ctx.GetServiceName().Source())
  46. if err != nil {
  47. return err
  48. }
  49. fileName := filepath.Join(ctx.GetMain().Filename, fmt.Sprintf("%v.go", mainFilename))
  50. imports := make([]string, 0)
  51. pbImport := fmt.Sprintf(`"%v"`, ctx.GetPb().Package)
  52. svcImport := fmt.Sprintf(`"%v"`, ctx.GetSvc().Package)
  53. remoteImport := fmt.Sprintf(`"%v"`, ctx.GetServer().Package)
  54. configImport := fmt.Sprintf(`"%v"`, ctx.GetConfig().Package)
  55. imports = append(imports, configImport, pbImport, remoteImport, svcImport)
  56. text, err := util.LoadTemplate(category, mainTemplateFile, mainTemplate)
  57. if err != nil {
  58. return err
  59. }
  60. etcFileName, err := format.FileNamingFormat(cfg.NamingFormat, ctx.GetServiceName().Source())
  61. if err != nil {
  62. return err
  63. }
  64. return util.With("main").GoFmt(true).Parse(text).SaveTo(map[string]interface{}{
  65. "serviceName": etcFileName,
  66. "imports": strings.Join(imports, util.NL),
  67. "pkg": proto.PbPackage,
  68. "serviceNew": stringx.From(proto.Service.Name).ToCamel(),
  69. "service": parser.CamelCase(proto.Service.Name),
  70. }, fileName, false)
  71. }