genhandlers.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. package gogen
  2. import (
  3. "fmt"
  4. "path"
  5. "strings"
  6. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  7. "github.com/tal-tech/go-zero/tools/goctl/config"
  8. "github.com/tal-tech/go-zero/tools/goctl/internal/env"
  9. "github.com/tal-tech/go-zero/tools/goctl/util"
  10. "github.com/tal-tech/go-zero/tools/goctl/util/format"
  11. "github.com/tal-tech/go-zero/tools/goctl/vars"
  12. )
  13. const handlerTemplate = `package handler
  14. import (
  15. "net/http"
  16. {{if .After1_1_10}}"github.com/tal-tech/go-zero/rest/httpx"{{end}}
  17. {{.ImportPackages}}
  18. )
  19. func {{.HandlerName}}(ctx *svc.ServiceContext) http.HandlerFunc {
  20. return func(w http.ResponseWriter, r *http.Request) {
  21. {{if .HasRequest}}var req types.{{.RequestType}}
  22. if err := httpx.Parse(r, &req); err != nil {
  23. httpx.Error(w, err)
  24. return
  25. }{{end}}
  26. l := logic.New{{.LogicType}}(r.Context(), ctx)
  27. {{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}req{{end}})
  28. if err != nil {
  29. httpx.Error(w, err)
  30. } else {
  31. {{if .HasResp}}httpx.OkJson(w, resp){{else}}httpx.Ok(w){{end}}
  32. }
  33. }
  34. }
  35. `
  36. type handlerInfo struct {
  37. ImportPackages string
  38. HandlerName string
  39. RequestType string
  40. LogicType string
  41. Call string
  42. HasResp bool
  43. HasRequest bool
  44. After1_1_10 bool
  45. }
  46. func genHandler(dir, rootPkg string, cfg *config.Config, group spec.Group, route spec.Route) error {
  47. handler := getHandlerName(route)
  48. if getHandlerFolderPath(group, route) != handlerDir {
  49. handler = strings.Title(handler)
  50. }
  51. goctlVersion := env.GetGoctlVersion()
  52. // todo(anqiansong): This will be removed after a certain number of production versions of goctl (probably 5)
  53. after1_1_10 := env.IsVersionGatherThan(goctlVersion, "1.1.10")
  54. return doGenToFile(dir, handler, cfg, group, route, handlerInfo{
  55. ImportPackages: genHandlerImports(group, route, rootPkg),
  56. HandlerName: handler,
  57. After1_1_10: after1_1_10,
  58. RequestType: util.Title(route.RequestTypeName()),
  59. LogicType: strings.Title(getLogicName(route)),
  60. Call: strings.Title(strings.TrimSuffix(handler, "Handler")),
  61. HasResp: len(route.ResponseTypeName()) > 0,
  62. HasRequest: len(route.RequestTypeName()) > 0,
  63. })
  64. }
  65. func doGenToFile(dir, handler string, cfg *config.Config, group spec.Group,
  66. route spec.Route, handleObj handlerInfo) error {
  67. filename, err := format.FileNamingFormat(cfg.NamingFormat, handler)
  68. if err != nil {
  69. return err
  70. }
  71. return genFile(fileGenConfig{
  72. dir: dir,
  73. subdir: getHandlerFolderPath(group, route),
  74. filename: filename + ".go",
  75. templateName: "handlerTemplate",
  76. category: category,
  77. templateFile: handlerTemplateFile,
  78. builtinTemplate: handlerTemplate,
  79. data: handleObj,
  80. })
  81. }
  82. func genHandlers(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
  83. for _, group := range api.Service.Groups {
  84. for _, route := range group.Routes {
  85. if err := genHandler(dir, rootPkg, cfg, group, route); err != nil {
  86. return err
  87. }
  88. }
  89. }
  90. return nil
  91. }
  92. func genHandlerImports(group spec.Group, route spec.Route, parentPkg string) string {
  93. var imports []string
  94. imports = append(imports, fmt.Sprintf("\"%s\"",
  95. util.JoinPackages(parentPkg, getLogicFolderPath(group, route))))
  96. imports = append(imports, fmt.Sprintf("\"%s\"", util.JoinPackages(parentPkg, contextDir)))
  97. if len(route.RequestTypeName()) > 0 {
  98. imports = append(imports, fmt.Sprintf("\"%s\"\n", util.JoinPackages(parentPkg, typesDir)))
  99. }
  100. currentVersion := env.GetGoctlVersion()
  101. // todo(anqiansong): This will be removed after a certain number of production versions of goctl (probably 5)
  102. if !env.IsVersionGatherThan(currentVersion, "1.1.10") {
  103. imports = append(imports, fmt.Sprintf("\"%s/rest/httpx\"", vars.ProjectOpenSourceURL))
  104. }
  105. return strings.Join(imports, "\n\t")
  106. }
  107. func getHandlerBaseName(route spec.Route) (string, error) {
  108. handler := route.Handler
  109. handler = strings.TrimSpace(handler)
  110. handler = strings.TrimSuffix(handler, "handler")
  111. handler = strings.TrimSuffix(handler, "Handler")
  112. return handler, nil
  113. }
  114. func getHandlerFolderPath(group spec.Group, route spec.Route) string {
  115. folder := route.GetAnnotation(groupProperty)
  116. if len(folder) == 0 {
  117. folder = group.GetAnnotation(groupProperty)
  118. if len(folder) == 0 {
  119. return handlerDir
  120. }
  121. }
  122. folder = strings.TrimPrefix(folder, "/")
  123. folder = strings.TrimSuffix(folder, "/")
  124. return path.Join(handlerDir, folder)
  125. }
  126. func getHandlerName(route spec.Route) string {
  127. handler, err := getHandlerBaseName(route)
  128. if err != nil {
  129. panic(err)
  130. }
  131. return handler + "Handler"
  132. }
  133. func getLogicName(route spec.Route) string {
  134. handler, err := getHandlerBaseName(route)
  135. if err != nil {
  136. panic(err)
  137. }
  138. return handler + "Logic"
  139. }