genmain.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package gogen
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  6. "github.com/tal-tech/go-zero/tools/goctl/config"
  7. ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
  8. "github.com/tal-tech/go-zero/tools/goctl/util/format"
  9. "github.com/tal-tech/go-zero/tools/goctl/vars"
  10. )
  11. const mainTemplate = `package main
  12. import (
  13. "flag"
  14. "fmt"
  15. {{.importPackages}}
  16. )
  17. var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file")
  18. func main() {
  19. flag.Parse()
  20. var c config.Config
  21. conf.MustLoad(*configFile, &c)
  22. ctx := svc.NewServiceContext(c)
  23. server := rest.MustNewServer(c.RestConf)
  24. defer server.Stop()
  25. handler.RegisterHandlers(server, ctx)
  26. fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
  27. server.Start()
  28. }
  29. `
  30. func genMain(dir string, cfg *config.Config, api *spec.ApiSpec) error {
  31. name := strings.ToLower(api.Service.Name)
  32. if strings.HasSuffix(name, "-api") {
  33. name = strings.ReplaceAll(name, "-api", "")
  34. }
  35. filename, err := format.FileNamingFormat(cfg.NamingFormat, name)
  36. if err != nil {
  37. return err
  38. }
  39. parentPkg, err := getParentPackage(dir)
  40. if err != nil {
  41. return err
  42. }
  43. return genFile(fileGenConfig{
  44. dir: dir,
  45. subdir: "",
  46. filename: filename + ".go",
  47. templateName: "mainTemplate",
  48. category: category,
  49. templateFile: mainTemplateFile,
  50. builtinTemplate: mainTemplate,
  51. data: map[string]string{
  52. "importPackages": genMainImports(parentPkg),
  53. "serviceName": api.Service.Name,
  54. },
  55. })
  56. }
  57. func genMainImports(parentPkg string) string {
  58. var imports []string
  59. imports = append(imports, fmt.Sprintf("\"%s\"", ctlutil.JoinPackages(parentPkg, configDir)))
  60. imports = append(imports, fmt.Sprintf("\"%s\"", ctlutil.JoinPackages(parentPkg, handlerDir)))
  61. imports = append(imports, fmt.Sprintf("\"%s\"\n", ctlutil.JoinPackages(parentPkg, contextDir)))
  62. imports = append(imports, fmt.Sprintf("\"%s/core/conf\"", vars.ProjectOpenSourceURL))
  63. imports = append(imports, fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL))
  64. return strings.Join(imports, "\n\t")
  65. }