genmain.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package gogen
  2. import (
  3. "fmt"
  4. "strings"
  5. "git.i2edu.net/i2/go-zero/tools/goctl/api/spec"
  6. "git.i2edu.net/i2/go-zero/tools/goctl/config"
  7. ctlutil "git.i2edu.net/i2/go-zero/tools/goctl/util"
  8. "git.i2edu.net/i2/go-zero/tools/goctl/util/format"
  9. "git.i2edu.net/i2/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, rootPkg 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. return genFile(fileGenConfig{
  40. dir: dir,
  41. subdir: "",
  42. filename: filename + ".go",
  43. templateName: "mainTemplate",
  44. category: category,
  45. templateFile: mainTemplateFile,
  46. builtinTemplate: mainTemplate,
  47. data: map[string]string{
  48. "importPackages": genMainImports(rootPkg),
  49. "serviceName": api.Service.Name,
  50. },
  51. })
  52. }
  53. func genMainImports(parentPkg string) string {
  54. var imports []string
  55. imports = append(imports, fmt.Sprintf("\"%s\"", ctlutil.JoinPackages(parentPkg, configDir)))
  56. imports = append(imports, fmt.Sprintf("\"%s\"", ctlutil.JoinPackages(parentPkg, handlerDir)))
  57. imports = append(imports, fmt.Sprintf("\"%s\"\n", ctlutil.JoinPackages(parentPkg, contextDir)))
  58. imports = append(imports, fmt.Sprintf("\"%s/core/conf\"", vars.ProjectOpenSourceURL))
  59. imports = append(imports, fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL))
  60. return strings.Join(imports, "\n\t")
  61. }