genhandlers.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util"
  10. "github.com/tal-tech/go-zero/tools/goctl/templatex"
  11. "github.com/tal-tech/go-zero/tools/goctl/util"
  12. "github.com/tal-tech/go-zero/tools/goctl/vars"
  13. )
  14. const handlerTemplate = `package handler
  15. import (
  16. "net/http"
  17. {{.ImportPackages}}
  18. )
  19. func {{.HandlerName}}(ctx *svc.ServiceContext) http.HandlerFunc {
  20. return func(w http.ResponseWriter, r *http.Request) {
  21. var req types.{{.RequestType}}
  22. if err := httpx.Parse(r, &req); err != nil {
  23. httpx.Error(w, err)
  24. return
  25. }
  26. l := logic.New{{.LogicType}}(r.Context(), ctx)
  27. {{if .HasResp}}resp, {{end}}err := l.{{.Call}}(req)
  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 Handler struct {
  37. ImportPackages string
  38. HandlerName string
  39. RequestType string
  40. LogicType string
  41. Call string
  42. HasResp bool
  43. }
  44. func genHandler(dir string, group spec.Group, route spec.Route) error {
  45. handler, ok := apiutil.GetAnnotationValue(route.Annotations, "server", "handler")
  46. if !ok {
  47. return fmt.Errorf("missing handler annotation for %q", route.Path)
  48. }
  49. handler = getHandlerName(handler)
  50. if getHandlerFolderPath(group, route) != handlerDir {
  51. handler = strings.Title(handler)
  52. }
  53. parentPkg, err := getParentPackage(dir)
  54. if err != nil {
  55. return err
  56. }
  57. return doGenToFile(dir, handler, group, route, Handler{
  58. ImportPackages: genHandlerImports(group, route, parentPkg),
  59. HandlerName: handler,
  60. RequestType: util.Title(route.RequestType.Name),
  61. LogicType: strings.TrimSuffix(strings.Title(handler), "Handler") + "Logic",
  62. Call: strings.Title(strings.TrimSuffix(handler, "Handler")),
  63. HasResp: len(route.ResponseType.Name) > 0,
  64. })
  65. }
  66. func doGenToFile(dir, handler string, group spec.Group, route spec.Route, handleObj Handler) error {
  67. if getHandlerFolderPath(group, route) != handlerDir {
  68. handler = strings.Title(handler)
  69. }
  70. filename := strings.ToLower(handler)
  71. if strings.HasSuffix(filename, "handler") {
  72. filename = filename + ".go"
  73. } else {
  74. filename = filename + "handler.go"
  75. }
  76. fp, created, err := apiutil.MaybeCreateFile(dir, getHandlerFolderPath(group, route), filename)
  77. if err != nil {
  78. return err
  79. }
  80. if !created {
  81. return nil
  82. }
  83. defer fp.Close()
  84. text, err := templatex.LoadTemplate(category, handlerTemplateFile, handlerTemplate)
  85. if err != nil {
  86. return err
  87. }
  88. buffer := new(bytes.Buffer)
  89. err = template.Must(template.New("handlerTemplate").Parse(text)).Execute(buffer, handleObj)
  90. if err != nil {
  91. return nil
  92. }
  93. formatCode := formatCode(buffer.String())
  94. _, err = fp.WriteString(formatCode)
  95. return err
  96. }
  97. func genHandlers(dir string, api *spec.ApiSpec) error {
  98. for _, group := range api.Service.Groups {
  99. for _, route := range group.Routes {
  100. if err := genHandler(dir, group, route); err != nil {
  101. return err
  102. }
  103. }
  104. }
  105. return nil
  106. }
  107. func genHandlerImports(group spec.Group, route spec.Route, parentPkg string) string {
  108. var imports []string
  109. imports = append(imports, fmt.Sprintf("\"%s\"",
  110. util.JoinPackages(parentPkg, getLogicFolderPath(group, route))))
  111. imports = append(imports, fmt.Sprintf("\"%s\"", util.JoinPackages(parentPkg, contextDir)))
  112. if len(route.RequestType.Name) > 0 {
  113. imports = append(imports, fmt.Sprintf("\"%s\"\n", util.JoinPackages(parentPkg, typesDir)))
  114. }
  115. imports = append(imports, fmt.Sprintf("\"%s/rest/httpx\"", vars.ProjectOpenSourceUrl))
  116. return strings.Join(imports, "\n\t")
  117. }
  118. func getHandlerBaseName(handler string) string {
  119. handlerName := util.Untitle(handler)
  120. if strings.HasSuffix(handlerName, "handler") {
  121. handlerName = strings.ReplaceAll(handlerName, "handler", "")
  122. } else if strings.HasSuffix(handlerName, "Handler") {
  123. handlerName = strings.ReplaceAll(handlerName, "Handler", "")
  124. }
  125. return handlerName
  126. }
  127. func getHandlerFolderPath(group spec.Group, route spec.Route) string {
  128. folder, ok := apiutil.GetAnnotationValue(route.Annotations, "server", groupProperty)
  129. if !ok {
  130. folder, ok = apiutil.GetAnnotationValue(group.Annotations, "server", groupProperty)
  131. if !ok {
  132. return handlerDir
  133. }
  134. }
  135. folder = strings.TrimPrefix(folder, "/")
  136. folder = strings.TrimSuffix(folder, "/")
  137. return path.Join(handlerDir, folder)
  138. }
  139. func getHandlerName(handler string) string {
  140. return getHandlerBaseName(handler) + "Handler"
  141. }