genhandlers.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. package gogen
  2. import (
  3. "errors"
  4. "fmt"
  5. "path"
  6. "strings"
  7. "unicode"
  8. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  9. apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util"
  10. "github.com/tal-tech/go-zero/tools/goctl/config"
  11. "github.com/tal-tech/go-zero/tools/goctl/util"
  12. "github.com/tal-tech/go-zero/tools/goctl/util/format"
  13. "github.com/tal-tech/go-zero/tools/goctl/vars"
  14. )
  15. const handlerTemplate = `package handler
  16. import (
  17. "net/http"
  18. {{.ImportPackages}}
  19. )
  20. func {{.HandlerName}}(ctx *svc.ServiceContext) http.HandlerFunc {
  21. return func(w http.ResponseWriter, r *http.Request) {
  22. {{if .HasRequest}}var req types.{{.RequestType}}
  23. if err := httpx.Parse(r, &req); err != nil {
  24. httpx.Error(w, err)
  25. return
  26. }{{end}}
  27. l := logic.New{{.LogicType}}(r.Context(), ctx)
  28. {{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}req{{end}})
  29. if err != nil {
  30. httpx.Error(w, err)
  31. } else {
  32. {{if .HasResp}}httpx.OkJson(w, resp){{else}}httpx.Ok(w){{end}}
  33. }
  34. }
  35. }
  36. `
  37. type Handler struct {
  38. ImportPackages string
  39. HandlerName string
  40. RequestType string
  41. LogicType string
  42. Call string
  43. HasResp bool
  44. HasRequest bool
  45. }
  46. func genHandler(dir 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. parentPkg, err := getParentPackage(dir)
  52. if err != nil {
  53. return err
  54. }
  55. return doGenToFile(dir, handler, cfg, group, route, Handler{
  56. ImportPackages: genHandlerImports(group, route, parentPkg),
  57. HandlerName: handler,
  58. RequestType: util.Title(route.RequestType.Name),
  59. LogicType: strings.Title(getLogicName(route)),
  60. Call: strings.Title(strings.TrimSuffix(handler, "Handler")),
  61. HasResp: len(route.ResponseType.Name) > 0,
  62. HasRequest: len(route.RequestType.Name) > 0,
  63. })
  64. }
  65. func doGenToFile(dir, handler string, cfg *config.Config, group spec.Group,
  66. route spec.Route, handleObj Handler) 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 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, 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.RequestType.Name) > 0 {
  98. imports = append(imports, fmt.Sprintf("\"%s\"\n", util.JoinPackages(parentPkg, typesDir)))
  99. }
  100. imports = append(imports, fmt.Sprintf("\"%s/rest/httpx\"", vars.ProjectOpenSourceUrl))
  101. return strings.Join(imports, "\n\t")
  102. }
  103. func getHandlerBaseName(route spec.Route) (string, error) {
  104. handler, ok := apiutil.GetAnnotationValue(route.Annotations, "server", "handler")
  105. if !ok {
  106. return "", fmt.Errorf("missing handler annotation for %q", route.Path)
  107. }
  108. for _, char := range handler {
  109. if !unicode.IsDigit(char) && !unicode.IsLetter(char) {
  110. return "", errors.New(fmt.Sprintf("route [%s] handler [%s] invalid, handler name should only contains letter or digit",
  111. route.Path, handler))
  112. }
  113. }
  114. handler = strings.TrimSpace(handler)
  115. handler = strings.TrimSuffix(handler, "handler")
  116. handler = strings.TrimSuffix(handler, "Handler")
  117. return handler, nil
  118. }
  119. func getHandlerFolderPath(group spec.Group, route spec.Route) string {
  120. folder, ok := apiutil.GetAnnotationValue(route.Annotations, "server", groupProperty)
  121. if !ok {
  122. folder, ok = apiutil.GetAnnotationValue(group.Annotations, "server", groupProperty)
  123. if !ok {
  124. return handlerDir
  125. }
  126. }
  127. folder = strings.TrimPrefix(folder, "/")
  128. folder = strings.TrimSuffix(folder, "/")
  129. return path.Join(handlerDir, folder)
  130. }
  131. func getHandlerName(route spec.Route) string {
  132. handler, err := getHandlerBaseName(route)
  133. if err != nil {
  134. panic(err)
  135. }
  136. return handler + "Handler"
  137. }
  138. func getLogicName(route spec.Route) string {
  139. handler, err := getHandlerBaseName(route)
  140. if err != nil {
  141. panic(err)
  142. }
  143. return handler + "Logic"
  144. }