genroutes.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. package gogen
  2. import (
  3. "fmt"
  4. "os"
  5. "path"
  6. "sort"
  7. "strings"
  8. "text/template"
  9. "github.com/tal-tech/go-zero/core/collection"
  10. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  11. "github.com/tal-tech/go-zero/tools/goctl/config"
  12. "github.com/tal-tech/go-zero/tools/goctl/util"
  13. "github.com/tal-tech/go-zero/tools/goctl/util/format"
  14. "github.com/tal-tech/go-zero/tools/goctl/vars"
  15. )
  16. const (
  17. routesFilename = "routes"
  18. routesTemplate = `// Code generated by goctl. DO NOT EDIT.
  19. package handler
  20. import (
  21. "net/http"
  22. {{.importPackages}}
  23. )
  24. func RegisterHandlers(engine *rest.Server, serverCtx *svc.ServiceContext) {
  25. {{.routesAdditions}}
  26. }
  27. `
  28. routesAdditionTemplate = `
  29. engine.AddRoutes(
  30. {{.routes}} {{.jwt}}{{.signature}}
  31. )
  32. `
  33. )
  34. var mapping = map[string]string{
  35. "delete": "http.MethodDelete",
  36. "get": "http.MethodGet",
  37. "head": "http.MethodHead",
  38. "post": "http.MethodPost",
  39. "put": "http.MethodPut",
  40. "patch": "http.MethodPatch",
  41. }
  42. type (
  43. group struct {
  44. routes []route
  45. jwtEnabled bool
  46. signatureEnabled bool
  47. authName string
  48. middlewares []string
  49. }
  50. route struct {
  51. method string
  52. path string
  53. handler string
  54. }
  55. )
  56. func genRoutes(dir string, cfg *config.Config, api *spec.ApiSpec) error {
  57. var builder strings.Builder
  58. groups, err := getRoutes(api)
  59. if err != nil {
  60. return err
  61. }
  62. gt := template.Must(template.New("groupTemplate").Parse(routesAdditionTemplate))
  63. for _, g := range groups {
  64. var gbuilder strings.Builder
  65. gbuilder.WriteString("[]rest.Route{")
  66. for _, r := range g.routes {
  67. fmt.Fprintf(&gbuilder, `
  68. {
  69. Method: %s,
  70. Path: "%s",
  71. Handler: %s,
  72. },`,
  73. r.method, r.path, r.handler)
  74. }
  75. var jwt string
  76. if g.jwtEnabled {
  77. jwt = fmt.Sprintf("\n rest.WithJwt(serverCtx.Config.%s.AccessSecret),", g.authName)
  78. }
  79. var signature string
  80. if g.signatureEnabled {
  81. signature = "\n rest.WithSignature(serverCtx.Config.Signature),"
  82. }
  83. var routes string
  84. if len(g.middlewares) > 0 {
  85. gbuilder.WriteString("\n}...,")
  86. var params = g.middlewares
  87. for i := range params {
  88. params[i] = "serverCtx." + params[i]
  89. }
  90. var middlewareStr = strings.Join(params, ", ")
  91. routes = fmt.Sprintf("rest.WithMiddlewares(\n[]rest.Middleware{ %s }, \n %s \n),",
  92. middlewareStr, strings.TrimSpace(gbuilder.String()))
  93. } else {
  94. gbuilder.WriteString("\n},")
  95. routes = strings.TrimSpace(gbuilder.String())
  96. }
  97. if err := gt.Execute(&builder, map[string]string{
  98. "routes": routes,
  99. "jwt": jwt,
  100. "signature": signature,
  101. }); err != nil {
  102. return err
  103. }
  104. }
  105. parentPkg, err := getParentPackage(dir)
  106. if err != nil {
  107. return err
  108. }
  109. routeFilename, err := format.FileNamingFormat(cfg.NamingFormat, routesFilename)
  110. if err != nil {
  111. return err
  112. }
  113. routeFilename = routeFilename + ".go"
  114. filename := path.Join(dir, handlerDir, routeFilename)
  115. os.Remove(filename)
  116. return genFile(fileGenConfig{
  117. dir: dir,
  118. subdir: handlerDir,
  119. filename: routeFilename,
  120. templateName: "routesTemplate",
  121. category: "",
  122. templateFile: "",
  123. builtinTemplate: routesTemplate,
  124. data: map[string]string{
  125. "importPackages": genRouteImports(parentPkg, api),
  126. "routesAdditions": strings.TrimSpace(builder.String()),
  127. },
  128. })
  129. }
  130. func genRouteImports(parentPkg string, api *spec.ApiSpec) string {
  131. var importSet = collection.NewSet()
  132. importSet.AddStr(fmt.Sprintf("\"%s\"", util.JoinPackages(parentPkg, contextDir)))
  133. for _, group := range api.Service.Groups {
  134. for _, route := range group.Routes {
  135. folder := route.GetAnnotation(groupProperty)
  136. if len(folder) == 0 {
  137. folder = group.GetAnnotation(groupProperty)
  138. if len(folder) == 0 {
  139. continue
  140. }
  141. }
  142. importSet.AddStr(fmt.Sprintf("%s \"%s\"", toPrefix(folder), util.JoinPackages(parentPkg, handlerDir, folder)))
  143. }
  144. }
  145. imports := importSet.KeysStr()
  146. sort.Strings(imports)
  147. projectSection := strings.Join(imports, "\n\t")
  148. depSection := fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL)
  149. return fmt.Sprintf("%s\n\n\t%s", projectSection, depSection)
  150. }
  151. func getRoutes(api *spec.ApiSpec) ([]group, error) {
  152. var routes []group
  153. for _, g := range api.Service.Groups {
  154. var groupedRoutes group
  155. for _, r := range g.Routes {
  156. handler := getHandlerName(r)
  157. handler = handler + "(serverCtx)"
  158. folder := r.GetAnnotation(groupProperty)
  159. if len(folder) > 0 {
  160. handler = toPrefix(folder) + "." + strings.ToUpper(handler[:1]) + handler[1:]
  161. } else {
  162. folder = g.GetAnnotation(groupProperty)
  163. if len(folder) > 0 {
  164. handler = toPrefix(folder) + "." + strings.ToUpper(handler[:1]) + handler[1:]
  165. }
  166. }
  167. groupedRoutes.routes = append(groupedRoutes.routes, route{
  168. method: mapping[r.Method],
  169. path: r.Path,
  170. handler: handler,
  171. })
  172. }
  173. jwt := g.GetAnnotation("jwt")
  174. if len(jwt) > 0 {
  175. groupedRoutes.authName = jwt
  176. groupedRoutes.jwtEnabled = true
  177. }
  178. signature := g.GetAnnotation("signature")
  179. if signature == "true" {
  180. groupedRoutes.signatureEnabled = true
  181. }
  182. middleware := g.GetAnnotation("middleware")
  183. if len(middleware) > 0 {
  184. for _, item := range strings.Split(middleware, ",") {
  185. groupedRoutes.middlewares = append(groupedRoutes.middlewares, item)
  186. }
  187. }
  188. routes = append(routes, groupedRoutes)
  189. }
  190. return routes, nil
  191. }
  192. func toPrefix(folder string) string {
  193. return strings.ReplaceAll(folder, "/", "")
  194. }