genmain.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 = `{{.head}}
  13. package main
  14. import (
  15. "flag"
  16. "fmt"
  17. {{.imports}}
  18. "github.com/tal-tech/go-zero/core/conf"
  19. "github.com/tal-tech/go-zero/zrpc"
  20. "google.golang.org/grpc"
  21. )
  22. var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file")
  23. func main() {
  24. flag.Parse()
  25. var c config.Config
  26. conf.MustLoad(*configFile, &c)
  27. ctx := svc.NewServiceContext(c)
  28. srv := server.New{{.serviceNew}}Server(ctx)
  29. s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
  30. {{.pkg}}.Register{{.service}}Server(grpcServer, srv)
  31. })
  32. defer s.Stop()
  33. fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
  34. s.Start()
  35. }
  36. `
  37. func (g *defaultGenerator) GenMain(ctx DirContext, proto parser.Proto, cfg *conf.Config) error {
  38. mainFilename, err := format.FileNamingFormat(cfg.NamingFormat, ctx.GetServiceName().Source())
  39. if err != nil {
  40. return err
  41. }
  42. fileName := filepath.Join(ctx.GetMain().Filename, fmt.Sprintf("%v.go", mainFilename))
  43. imports := make([]string, 0)
  44. pbImport := fmt.Sprintf(`"%v"`, ctx.GetPb().Package)
  45. svcImport := fmt.Sprintf(`"%v"`, ctx.GetSvc().Package)
  46. remoteImport := fmt.Sprintf(`"%v"`, ctx.GetServer().Package)
  47. configImport := fmt.Sprintf(`"%v"`, ctx.GetConfig().Package)
  48. imports = append(imports, configImport, pbImport, remoteImport, svcImport)
  49. head := util.GetHead(proto.Name)
  50. text, err := util.LoadTemplate(category, mainTemplateFile, mainTemplate)
  51. if err != nil {
  52. return err
  53. }
  54. return util.With("main").GoFmt(true).Parse(text).SaveTo(map[string]interface{}{
  55. "head": head,
  56. "serviceName": strings.ToLower(ctx.GetServiceName().ToCamel()),
  57. "imports": strings.Join(imports, util.NL),
  58. "pkg": proto.PbPackage,
  59. "serviceNew": stringx.From(proto.Service.Name).ToCamel(),
  60. "service": parser.CamelCase(proto.Service.Name),
  61. }, fileName, false)
  62. }