genmain.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package generator
  2. import (
  3. _ "embed"
  4. "fmt"
  5. "path/filepath"
  6. "strings"
  7. conf "github.com/zeromicro/go-zero/tools/goctl/config"
  8. "github.com/zeromicro/go-zero/tools/goctl/rpc/parser"
  9. "github.com/zeromicro/go-zero/tools/goctl/util"
  10. "github.com/zeromicro/go-zero/tools/goctl/util/format"
  11. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  12. "github.com/zeromicro/go-zero/tools/goctl/util/stringx"
  13. )
  14. //go:embed main.tpl
  15. var mainTemplate string
  16. // GenMain generates the main file of the rpc service, which is an rpc service program call entry
  17. func (g *Generator) GenMain(ctx DirContext, proto parser.Proto, cfg *conf.Config) error {
  18. mainFilename, err := format.FileNamingFormat(cfg.NamingFormat, ctx.GetServiceName().Source())
  19. if err != nil {
  20. return err
  21. }
  22. fileName := filepath.Join(ctx.GetMain().Filename, fmt.Sprintf("%v.go", mainFilename))
  23. imports := make([]string, 0)
  24. pbImport := fmt.Sprintf(`"%v"`, ctx.GetPb().Package)
  25. svcImport := fmt.Sprintf(`"%v"`, ctx.GetSvc().Package)
  26. remoteImport := fmt.Sprintf(`"%v"`, ctx.GetServer().Package)
  27. configImport := fmt.Sprintf(`"%v"`, ctx.GetConfig().Package)
  28. imports = append(imports, configImport, pbImport, remoteImport, svcImport)
  29. text, err := pathx.LoadTemplate(category, mainTemplateFile, mainTemplate)
  30. if err != nil {
  31. return err
  32. }
  33. etcFileName, err := format.FileNamingFormat(cfg.NamingFormat, ctx.GetServiceName().Source())
  34. if err != nil {
  35. return err
  36. }
  37. return util.With("main").GoFmt(true).Parse(text).SaveTo(map[string]interface{}{
  38. "serviceName": etcFileName,
  39. "imports": strings.Join(imports, pathx.NL),
  40. "pkg": proto.PbPackage,
  41. "serviceNew": stringx.From(proto.Service.Name).ToCamel(),
  42. "service": parser.CamelCase(proto.Service.Name),
  43. }, fileName, false)
  44. }