genroutes.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. package gogen
  2. import (
  3. "fmt"
  4. "os"
  5. "path"
  6. "sort"
  7. "strings"
  8. "text/template"
  9. "git.i2edu.net/i2/go-zero/core/collection"
  10. "git.i2edu.net/i2/go-zero/tools/goctl/api/spec"
  11. "git.i2edu.net/i2/go-zero/tools/goctl/config"
  12. "git.i2edu.net/i2/go-zero/tools/goctl/util"
  13. "git.i2edu.net/i2/go-zero/tools/goctl/util/format"
  14. "git.i2edu.net/i2/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, rootPkg 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. params := g.middlewares
  87. for i := range params {
  88. params[i] = "serverCtx." + params[i]
  89. }
  90. 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. routeFilename, err := format.FileNamingFormat(cfg.NamingFormat, routesFilename)
  106. if err != nil {
  107. return err
  108. }
  109. routeFilename = routeFilename + ".go"
  110. filename := path.Join(dir, handlerDir, routeFilename)
  111. os.Remove(filename)
  112. return genFile(fileGenConfig{
  113. dir: dir,
  114. subdir: handlerDir,
  115. filename: routeFilename,
  116. templateName: "routesTemplate",
  117. category: "",
  118. templateFile: "",
  119. builtinTemplate: routesTemplate,
  120. data: map[string]string{
  121. "importPackages": genRouteImports(rootPkg, api),
  122. "routesAdditions": strings.TrimSpace(builder.String()),
  123. },
  124. })
  125. }
  126. func genRouteImports(parentPkg string, api *spec.ApiSpec) string {
  127. importSet := collection.NewSet()
  128. importSet.AddStr(fmt.Sprintf("\"%s\"", util.JoinPackages(parentPkg, contextDir)))
  129. for _, group := range api.Service.Groups {
  130. for _, route := range group.Routes {
  131. folder := route.GetAnnotation(groupProperty)
  132. if len(folder) == 0 {
  133. folder = group.GetAnnotation(groupProperty)
  134. if len(folder) == 0 {
  135. continue
  136. }
  137. }
  138. importSet.AddStr(fmt.Sprintf("%s \"%s\"", toPrefix(folder), util.JoinPackages(parentPkg, handlerDir, folder)))
  139. }
  140. }
  141. imports := importSet.KeysStr()
  142. sort.Strings(imports)
  143. projectSection := strings.Join(imports, "\n\t")
  144. depSection := fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL)
  145. return fmt.Sprintf("%s\n\n\t%s", projectSection, depSection)
  146. }
  147. func getRoutes(api *spec.ApiSpec) ([]group, error) {
  148. var routes []group
  149. for _, g := range api.Service.Groups {
  150. var groupedRoutes group
  151. for _, r := range g.Routes {
  152. handler := getHandlerName(r)
  153. handler = handler + "(serverCtx)"
  154. folder := r.GetAnnotation(groupProperty)
  155. if len(folder) > 0 {
  156. handler = toPrefix(folder) + "." + strings.ToUpper(handler[:1]) + handler[1:]
  157. } else {
  158. folder = g.GetAnnotation(groupProperty)
  159. if len(folder) > 0 {
  160. handler = toPrefix(folder) + "." + strings.ToUpper(handler[:1]) + handler[1:]
  161. }
  162. }
  163. groupedRoutes.routes = append(groupedRoutes.routes, route{
  164. method: mapping[r.Method],
  165. path: r.Path,
  166. handler: handler,
  167. })
  168. }
  169. jwt := g.GetAnnotation("jwt")
  170. if len(jwt) > 0 {
  171. groupedRoutes.authName = jwt
  172. groupedRoutes.jwtEnabled = true
  173. }
  174. signature := g.GetAnnotation("signature")
  175. if signature == "true" {
  176. groupedRoutes.signatureEnabled = true
  177. }
  178. middleware := g.GetAnnotation("middleware")
  179. if len(middleware) > 0 {
  180. for _, item := range strings.Split(middleware, ",") {
  181. groupedRoutes.middlewares = append(groupedRoutes.middlewares, item)
  182. }
  183. }
  184. routes = append(routes, groupedRoutes)
  185. }
  186. return routes, nil
  187. }
  188. func toPrefix(folder string) string {
  189. return strings.ReplaceAll(folder, "/", "")
  190. }