You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/tools/goctl/api/gogen/genroutes.go

228 lines
5.6 KiB
Go

4 years ago
package gogen
import (
"fmt"
"os"
4 years ago
"path"
"sort"
"strings"
"text/template"
"github.com/tal-tech/go-zero/core/collection"
"github.com/tal-tech/go-zero/tools/goctl/api/spec"
"github.com/tal-tech/go-zero/tools/goctl/config"
"github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/util/format"
"github.com/tal-tech/go-zero/tools/goctl/vars"
4 years ago
)
const (
routesFilename = "routes"
routesTemplate = `// Code generated by goctl. DO NOT EDIT.
4 years ago
package handler
import (
"net/http"
{{.importPackages}}
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
4 years ago
{{.routesAdditions}}
}
`
routesAdditionTemplate = `
server.AddRoutes(
{{.routes}} {{.jwt}}{{.signature}} {{.prefix}}
)
4 years ago
`
)
var mapping = map[string]string{
"delete": "http.MethodDelete",
"get": "http.MethodGet",
"head": "http.MethodHead",
"post": "http.MethodPost",
"put": "http.MethodPut",
"patch": "http.MethodPatch",
"connect": "http.MethodConnect",
"options": "http.MethodOptions",
"trace": "http.MethodTrace",
4 years ago
}
type (
group struct {
routes []route
jwtEnabled bool
signatureEnabled bool
authName string
middlewares []string
prefix string
4 years ago
}
route struct {
method string
path string
handler string
}
)
func genRoutes(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
4 years ago
var builder strings.Builder
groups, err := getRoutes(api)
if err != nil {
return err
}
gt := template.Must(template.New("groupTemplate").Parse(routesAdditionTemplate))
for _, g := range groups {
var gbuilder strings.Builder
gbuilder.WriteString("[]rest.Route{")
4 years ago
for _, r := range g.routes {
fmt.Fprintf(&gbuilder, `
{
Method: %s,
Path: "%s",
Handler: %s,
},`,
r.method, r.path, r.handler)
}
4 years ago
var jwt string
4 years ago
if g.jwtEnabled {
jwt = fmt.Sprintf("\n rest.WithJwt(serverCtx.Config.%s.AccessSecret),", g.authName)
4 years ago
}
var signature, prefix string
4 years ago
if g.signatureEnabled {
signature = "\n rest.WithSignature(serverCtx.Config.Signature),"
4 years ago
}
if len(g.prefix) > 0 {
prefix = fmt.Sprintf(`
rest.WithPrefix("%s"),`, g.prefix)
}
var routes string
if len(g.middlewares) > 0 {
gbuilder.WriteString("\n}...,")
params := g.middlewares
for i := range params {
params[i] = "serverCtx." + params[i]
}
middlewareStr := strings.Join(params, ", ")
routes = fmt.Sprintf("rest.WithMiddlewares(\n[]rest.Middleware{ %s }, \n %s \n),",
middlewareStr, strings.TrimSpace(gbuilder.String()))
} else {
gbuilder.WriteString("\n},")
routes = strings.TrimSpace(gbuilder.String())
}
4 years ago
if err := gt.Execute(&builder, map[string]string{
"routes": routes,
4 years ago
"jwt": jwt,
"signature": signature,
"prefix": prefix,
4 years ago
}); err != nil {
return err
}
}
routeFilename, err := format.FileNamingFormat(cfg.NamingFormat, routesFilename)
if err != nil {
return err
}
routeFilename = routeFilename + ".go"
filename := path.Join(dir, handlerDir, routeFilename)
os.Remove(filename)
4 years ago
return genFile(fileGenConfig{
dir: dir,
subdir: handlerDir,
filename: routeFilename,
templateName: "routesTemplate",
category: "",
templateFile: "",
builtinTemplate: routesTemplate,
data: map[string]string{
"importPackages": genRouteImports(rootPkg, api),
"routesAdditions": strings.TrimSpace(builder.String()),
},
4 years ago
})
}
func genRouteImports(parentPkg string, api *spec.ApiSpec) string {
importSet := collection.NewSet()
importSet.AddStr(fmt.Sprintf("\"%s\"", util.JoinPackages(parentPkg, contextDir)))
4 years ago
for _, group := range api.Service.Groups {
for _, route := range group.Routes {
folder := route.GetAnnotation(groupProperty)
if len(folder) == 0 {
folder = group.GetAnnotation(groupProperty)
if len(folder) == 0 {
4 years ago
continue
}
}
importSet.AddStr(fmt.Sprintf("%s \"%s\"", toPrefix(folder), util.JoinPackages(parentPkg, handlerDir, folder)))
4 years ago
}
}
imports := importSet.KeysStr()
sort.Strings(imports)
projectSection := strings.Join(imports, "\n\t")
depSection := fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL)
return fmt.Sprintf("%s\n\n\t%s", projectSection, depSection)
4 years ago
}
func getRoutes(api *spec.ApiSpec) ([]group, error) {
var routes []group
for _, g := range api.Service.Groups {
var groupedRoutes group
for _, r := range g.Routes {
handler := getHandlerName(r)
handler = handler + "(serverCtx)"
folder := r.GetAnnotation(groupProperty)
if len(folder) > 0 {
handler = toPrefix(folder) + "." + strings.ToUpper(handler[:1]) + handler[1:]
4 years ago
} else {
folder = g.GetAnnotation(groupProperty)
if len(folder) > 0 {
handler = toPrefix(folder) + "." + strings.ToUpper(handler[:1]) + handler[1:]
4 years ago
}
}
groupedRoutes.routes = append(groupedRoutes.routes, route{
method: mapping[r.Method],
path: r.Path,
handler: handler,
})
}
jwt := g.GetAnnotation("jwt")
if len(jwt) > 0 {
groupedRoutes.authName = jwt
groupedRoutes.jwtEnabled = true
}
signature := g.GetAnnotation("signature")
if signature == "true" {
groupedRoutes.signatureEnabled = true
}
middleware := g.GetAnnotation("middleware")
if len(middleware) > 0 {
groupedRoutes.middlewares = append(groupedRoutes.middlewares,
strings.Split(middleware, ",")...)
}
prefix := g.GetAnnotation(spec.RoutePrefixKey)
prefix = strings.ReplaceAll(prefix, `"`, "")
prefix = strings.TrimSpace(prefix)
if len(prefix) > 0 {
prefix = path.Join("/", prefix)
groupedRoutes.prefix = prefix
}
4 years ago
routes = append(routes, groupedRoutes)
}
return routes, nil
}
func toPrefix(folder string) string {
return strings.ReplaceAll(folder, "/", "")
}