genmain.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package gen
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "strings"
  6. "github.com/tal-tech/go-zero/tools/goctl/rpc/parser"
  7. "github.com/tal-tech/go-zero/tools/goctl/util"
  8. )
  9. const mainTemplate = `{{.head}}
  10. package main
  11. import (
  12. "flag"
  13. "fmt"
  14. {{.imports}}
  15. "github.com/tal-tech/go-zero/core/conf"
  16. "github.com/tal-tech/go-zero/core/logx"
  17. "github.com/tal-tech/go-zero/zrpc"
  18. "google.golang.org/grpc"
  19. )
  20. var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file")
  21. func main() {
  22. flag.Parse()
  23. var c config.Config
  24. conf.MustLoad(*configFile, &c)
  25. ctx := svc.NewServiceContext(c)
  26. {{.srv}}
  27. s, err := zrpc.NewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
  28. {{.registers}}
  29. })
  30. logx.Must(err)
  31. fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
  32. s.Start()
  33. }
  34. `
  35. func (g *defaultRpcGenerator) genMain() error {
  36. mainPath := g.dirM[dirTarget]
  37. file := g.ast
  38. pkg := file.Package
  39. fileName := filepath.Join(mainPath, fmt.Sprintf("%v.go", g.Ctx.ServiceName.Lower()))
  40. imports := make([]string, 0)
  41. pbImport := fmt.Sprintf(`%v "%v"`, pkg, g.mustGetPackage(dirPb))
  42. svcImport := fmt.Sprintf(`"%v"`, g.mustGetPackage(dirSvc))
  43. remoteImport := fmt.Sprintf(`"%v"`, g.mustGetPackage(dirServer))
  44. configImport := fmt.Sprintf(`"%v"`, g.mustGetPackage(dirConfig))
  45. imports = append(imports, configImport, pbImport, remoteImport, svcImport)
  46. srv, registers := g.genServer(pkg, file.Service)
  47. head := util.GetHead(g.Ctx.ProtoSource)
  48. return util.With("main").GoFmt(true).Parse(mainTemplate).SaveTo(map[string]interface{}{
  49. "head": head,
  50. "package": pkg,
  51. "serviceName": g.Ctx.ServiceName.Lower(),
  52. "srv": srv,
  53. "registers": registers,
  54. "imports": strings.Join(imports, "\n"),
  55. }, fileName, true)
  56. }
  57. func (g *defaultRpcGenerator) genServer(pkg string, list []*parser.RpcService) (string, string) {
  58. list1 := make([]string, 0)
  59. list2 := make([]string, 0)
  60. for _, item := range list {
  61. name := item.Name.UnTitle()
  62. list1 = append(list1, fmt.Sprintf("%sSrv := server.New%sServer(ctx)", name, item.Name.Title()))
  63. list2 = append(list2, fmt.Sprintf("%s.Register%sServer(grpcServer, %sSrv)", pkg, item.Name.Title(), name))
  64. }
  65. return strings.Join(list1, "\n"), strings.Join(list2, "\n")
  66. }