genroutes.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package gogen
  2. import (
  3. "fmt"
  4. "os"
  5. "path"
  6. "sort"
  7. "strings"
  8. "text/template"
  9. "time"
  10. "github.com/zeromicro/go-zero/core/collection"
  11. "github.com/zeromicro/go-zero/tools/goctl/api/spec"
  12. "github.com/zeromicro/go-zero/tools/goctl/config"
  13. "github.com/zeromicro/go-zero/tools/goctl/util/format"
  14. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  15. "github.com/zeromicro/go-zero/tools/goctl/vars"
  16. )
  17. const (
  18. jwtTransKey = "jwtTransition"
  19. routesFilename = "routes"
  20. routesTemplate = `// Code generated by goctl. DO NOT EDIT.
  21. package handler
  22. import (
  23. "net/http"{{if .hasTimeout}}
  24. "time"{{end}}
  25. {{.importPackages}}
  26. )
  27. func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
  28. {{.routesAdditions}}
  29. }
  30. `
  31. routesAdditionTemplate = `
  32. server.AddRoutes(
  33. {{.routes}} {{.jwt}}{{.signature}} {{.prefix}} {{.timeout}}
  34. )
  35. `
  36. timeoutThreshold = time.Millisecond
  37. )
  38. var mapping = map[string]string{
  39. "delete": "http.MethodDelete",
  40. "get": "http.MethodGet",
  41. "head": "http.MethodHead",
  42. "post": "http.MethodPost",
  43. "put": "http.MethodPut",
  44. "patch": "http.MethodPatch",
  45. "connect": "http.MethodConnect",
  46. "options": "http.MethodOptions",
  47. "trace": "http.MethodTrace",
  48. }
  49. type (
  50. group struct {
  51. routes []route
  52. jwtEnabled bool
  53. signatureEnabled bool
  54. authName string
  55. timeout string
  56. middlewares []string
  57. prefix string
  58. jwtTrans string
  59. }
  60. route struct {
  61. method string
  62. path string
  63. handler string
  64. }
  65. )
  66. func genRoutes(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
  67. var builder strings.Builder
  68. groups, err := getRoutes(api)
  69. if err != nil {
  70. return err
  71. }
  72. templateText, err := pathx.LoadTemplate(category, routesAdditionTemplateFile, routesAdditionTemplate)
  73. if err != nil {
  74. return err
  75. }
  76. var hasTimeout bool
  77. gt := template.Must(template.New("groupTemplate").Parse(templateText))
  78. for _, g := range groups {
  79. var gbuilder strings.Builder
  80. gbuilder.WriteString("[]rest.Route{")
  81. for _, r := range g.routes {
  82. fmt.Fprintf(&gbuilder, `
  83. {
  84. Method: %s,
  85. Path: "%s",
  86. Handler: %s,
  87. },`,
  88. r.method, r.path, r.handler)
  89. }
  90. var jwt string
  91. if g.jwtEnabled {
  92. jwt = fmt.Sprintf("\n rest.WithJwt(serverCtx.Config.%s.AccessSecret),", g.authName)
  93. }
  94. if len(g.jwtTrans) > 0 {
  95. jwt = jwt + fmt.Sprintf("\n rest.WithJwtTransition(serverCtx.Config.%s.PrevSecret,serverCtx.Config.%s.Secret),", g.jwtTrans, g.jwtTrans)
  96. }
  97. var signature, prefix string
  98. if g.signatureEnabled {
  99. signature = "\n rest.WithSignature(serverCtx.Config.Signature),"
  100. }
  101. if len(g.prefix) > 0 {
  102. prefix = fmt.Sprintf(`
  103. rest.WithPrefix("%s"),`, g.prefix)
  104. }
  105. var timeout string
  106. if len(g.timeout) > 0 {
  107. duration, err := time.ParseDuration(g.timeout)
  108. if err != nil {
  109. return err
  110. }
  111. // why we check this, maybe some users set value 1, it's 1ns, not 1s.
  112. if duration < timeoutThreshold {
  113. return fmt.Errorf("timeout should not less than 1ms, now %v", duration)
  114. }
  115. timeout = fmt.Sprintf("rest.WithTimeout(%d * time.Millisecond),", duration/time.Millisecond)
  116. hasTimeout = true
  117. }
  118. var routes string
  119. if len(g.middlewares) > 0 {
  120. gbuilder.WriteString("\n}...,")
  121. params := g.middlewares
  122. for i := range params {
  123. params[i] = "serverCtx." + params[i]
  124. }
  125. middlewareStr := strings.Join(params, ", ")
  126. routes = fmt.Sprintf("rest.WithMiddlewares(\n[]rest.Middleware{ %s }, \n %s \n),",
  127. middlewareStr, strings.TrimSpace(gbuilder.String()))
  128. } else {
  129. gbuilder.WriteString("\n},")
  130. routes = strings.TrimSpace(gbuilder.String())
  131. }
  132. if err := gt.Execute(&builder, map[string]string{
  133. "routes": routes,
  134. "jwt": jwt,
  135. "signature": signature,
  136. "prefix": prefix,
  137. "timeout": timeout,
  138. }); err != nil {
  139. return err
  140. }
  141. }
  142. routeFilename, err := format.FileNamingFormat(cfg.NamingFormat, routesFilename)
  143. if err != nil {
  144. return err
  145. }
  146. routeFilename = routeFilename + ".go"
  147. filename := path.Join(dir, handlerDir, routeFilename)
  148. os.Remove(filename)
  149. return genFile(fileGenConfig{
  150. dir: dir,
  151. subdir: handlerDir,
  152. filename: routeFilename,
  153. templateName: "routesTemplate",
  154. category: category,
  155. templateFile: routesTemplateFile,
  156. builtinTemplate: routesTemplate,
  157. data: map[string]interface{}{
  158. "hasTimeout": hasTimeout,
  159. "importPackages": genRouteImports(rootPkg, api),
  160. "routesAdditions": strings.TrimSpace(builder.String()),
  161. },
  162. })
  163. }
  164. func genRouteImports(parentPkg string, api *spec.ApiSpec) string {
  165. importSet := collection.NewSet()
  166. importSet.AddStr(fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, contextDir)))
  167. for _, group := range api.Service.Groups {
  168. for _, route := range group.Routes {
  169. folder := route.GetAnnotation(groupProperty)
  170. if len(folder) == 0 {
  171. folder = group.GetAnnotation(groupProperty)
  172. if len(folder) == 0 {
  173. continue
  174. }
  175. }
  176. importSet.AddStr(fmt.Sprintf("%s \"%s\"", toPrefix(folder),
  177. pathx.JoinPackages(parentPkg, handlerDir, folder)))
  178. }
  179. }
  180. imports := importSet.KeysStr()
  181. sort.Strings(imports)
  182. projectSection := strings.Join(imports, "\n\t")
  183. depSection := fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL)
  184. return fmt.Sprintf("%s\n\n\t%s", projectSection, depSection)
  185. }
  186. func getRoutes(api *spec.ApiSpec) ([]group, error) {
  187. var routes []group
  188. for _, g := range api.Service.Groups {
  189. var groupedRoutes group
  190. for _, r := range g.Routes {
  191. handler := getHandlerName(r)
  192. handler = handler + "(serverCtx)"
  193. folder := r.GetAnnotation(groupProperty)
  194. if len(folder) > 0 {
  195. handler = toPrefix(folder) + "." + strings.ToUpper(handler[:1]) + handler[1:]
  196. } else {
  197. folder = g.GetAnnotation(groupProperty)
  198. if len(folder) > 0 {
  199. handler = toPrefix(folder) + "." + strings.ToUpper(handler[:1]) + handler[1:]
  200. }
  201. }
  202. groupedRoutes.routes = append(groupedRoutes.routes, route{
  203. method: mapping[r.Method],
  204. path: r.Path,
  205. handler: handler,
  206. })
  207. }
  208. groupedRoutes.timeout = g.GetAnnotation("timeout")
  209. jwt := g.GetAnnotation("jwt")
  210. if len(jwt) > 0 {
  211. groupedRoutes.authName = jwt
  212. groupedRoutes.jwtEnabled = true
  213. }
  214. jwtTrans := g.GetAnnotation(jwtTransKey)
  215. if len(jwtTrans) > 0 {
  216. groupedRoutes.jwtTrans = jwtTrans
  217. }
  218. signature := g.GetAnnotation("signature")
  219. if signature == "true" {
  220. groupedRoutes.signatureEnabled = true
  221. }
  222. middleware := g.GetAnnotation("middleware")
  223. if len(middleware) > 0 {
  224. groupedRoutes.middlewares = append(groupedRoutes.middlewares,
  225. strings.Split(middleware, ",")...)
  226. }
  227. prefix := g.GetAnnotation(spec.RoutePrefixKey)
  228. prefix = strings.ReplaceAll(prefix, `"`, "")
  229. prefix = strings.TrimSpace(prefix)
  230. if len(prefix) > 0 {
  231. prefix = path.Join("/", prefix)
  232. groupedRoutes.prefix = prefix
  233. }
  234. routes = append(routes, groupedRoutes)
  235. }
  236. return routes, nil
  237. }
  238. func toPrefix(folder string) string {
  239. return strings.ReplaceAll(folder, "/", "")
  240. }