genlogic.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. package gogen
  2. import (
  3. "bytes"
  4. "fmt"
  5. "path"
  6. "strings"
  7. "text/template"
  8. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  9. "github.com/tal-tech/go-zero/tools/goctl/api/util"
  10. ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
  11. "github.com/tal-tech/go-zero/tools/goctl/vars"
  12. )
  13. const logicTemplate = `package logic
  14. import (
  15. {{.imports}}
  16. )
  17. type {{.logic}} struct {
  18. ctx context.Context
  19. svcCtx *svc.ServiceContext
  20. logx.Logger
  21. }
  22. func New{{.logic}}(ctx context.Context, svcCtx *svc.ServiceContext) {{.logic}} {
  23. return {{.logic}}{
  24. ctx: ctx,
  25. svcCtx: svcCtx,
  26. Logger: logx.WithContext(ctx),
  27. }
  28. }
  29. func (l *{{.logic}}) {{.function}}({{.request}}) {{.responseType}} {
  30. {{.returnString}}
  31. }
  32. `
  33. func genLogic(dir string, api *spec.ApiSpec) error {
  34. for _, g := range api.Service.Groups {
  35. for _, r := range g.Routes {
  36. err := genLogicByRoute(dir, g, r)
  37. if err != nil {
  38. return err
  39. }
  40. }
  41. }
  42. return nil
  43. }
  44. func genLogicByRoute(dir string, group spec.Group, route spec.Route) error {
  45. handler, ok := util.GetAnnotationValue(route.Annotations, "server", "handler")
  46. if !ok {
  47. return fmt.Errorf("missing handler annotation for %q", route.Path)
  48. }
  49. handler = strings.TrimSuffix(handler, "handler")
  50. handler = strings.TrimSuffix(handler, "Handler")
  51. filename := strings.ToLower(handler)
  52. goFile := filename + "logic.go"
  53. fp, created, err := util.MaybeCreateFile(dir, getLogicFolderPath(group, route), goFile)
  54. if err != nil {
  55. return err
  56. }
  57. if !created {
  58. return nil
  59. }
  60. defer fp.Close()
  61. parentPkg, err := getParentPackage(dir)
  62. if err != nil {
  63. return err
  64. }
  65. imports := genLogicImports(route, parentPkg)
  66. responseString := ""
  67. returnString := ""
  68. requestString := ""
  69. if len(route.ResponseType.Name) > 0 {
  70. resp := strings.Title(route.ResponseType.Name)
  71. responseString = "(*types." + resp + ", error)"
  72. returnString = fmt.Sprintf("return &types.%s{}, nil", resp)
  73. } else {
  74. responseString = "error"
  75. returnString = "return nil"
  76. }
  77. if len(route.RequestType.Name) > 0 {
  78. requestString = "req " + "types." + strings.Title(route.RequestType.Name)
  79. }
  80. t := template.Must(template.New("logicTemplate").Parse(logicTemplate))
  81. buffer := new(bytes.Buffer)
  82. err = t.Execute(fp, map[string]string{
  83. "imports": imports,
  84. "logic": strings.Title(handler) + "Logic",
  85. "function": strings.Title(strings.TrimSuffix(handler, "Handler")),
  86. "responseType": responseString,
  87. "returnString": returnString,
  88. "request": requestString,
  89. })
  90. if err != nil {
  91. return err
  92. }
  93. formatCode := formatCode(buffer.String())
  94. _, err = fp.WriteString(formatCode)
  95. return err
  96. }
  97. func getLogicFolderPath(group spec.Group, route spec.Route) string {
  98. folder, ok := util.GetAnnotationValue(route.Annotations, "server", folderProperty)
  99. if !ok {
  100. folder, ok = util.GetAnnotationValue(group.Annotations, "server", folderProperty)
  101. if !ok {
  102. return logicDir
  103. }
  104. }
  105. folder = strings.TrimPrefix(folder, "/")
  106. folder = strings.TrimSuffix(folder, "/")
  107. return path.Join(logicDir, folder)
  108. }
  109. func genLogicImports(route spec.Route, parentPkg string) string {
  110. var imports []string
  111. imports = append(imports, `"context"`+"\n")
  112. imports = append(imports, fmt.Sprintf("\"%s\"", ctlutil.JoinPackages(parentPkg, contextDir)))
  113. if len(route.ResponseType.Name) > 0 || len(route.RequestType.Name) > 0 {
  114. imports = append(imports, fmt.Sprintf("\"%s\"\n", ctlutil.JoinPackages(parentPkg, typesDir)))
  115. }
  116. imports = append(imports, fmt.Sprintf("\"%s/core/logx\"", vars.ProjectOpenSourceUrl))
  117. return strings.Join(imports, "\n\t")
  118. }