genhandlers.go 4.5 KB

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