diff --git a/.template/plugins/api/route2code.go.tpl b/.template/plugins/api/route2code.go.tpl index 8fb69e30..06065c72 100644 --- a/.template/plugins/api/route2code.go.tpl +++ b/.template/plugins/api/route2code.go.tpl @@ -3,9 +3,10 @@ package handler import ( - "fmt" "net/http" "strings" + + casbinutil "github.com/casbin/casbin/v2/util" ) var routesCodesMap = map[string]string{ @@ -14,7 +15,12 @@ var routesCodesMap = map[string]string{ } func Route2Code(r *http.Request) string { - path := r.URL.Path - method := r.Method - return routesCodesMap[fmt.Sprintf("%s:%s", strings.ToUpper(method), path)] + for k, v := range routesCodesMap { + if splits := strings.Split(k, ":"); len(splits) >= 2 && splits[0] == strings.ToUpper(r.Method) { + if casbinutil.KeyMatch2(r.URL.Path, strings.Join(splits[1:], ":")) { + return v + } + } + } + return "unknown_code" } diff --git a/internal/gen/genapi/gen.go b/internal/gen/genapi/gen.go index 8e234e3c..ec7c8f10 100644 --- a/internal/gen/genapi/gen.go +++ b/internal/gen/genapi/gen.go @@ -286,6 +286,7 @@ func (ja *JzeroApi) generateApiCode() error { } if ja.Route2Code { + fmt.Printf("%s to generate internal/handler/route2code.go\n", color.WithColor("Start", color.FgGreen)) if route2CodeBytes, err := ja.genRoute2Code(); err != nil { return err } else { @@ -293,6 +294,7 @@ func (ja *JzeroApi) generateApiCode() error { return err } } + fmt.Printf("%s", color.WithColor("Done\n", color.FgGreen)) } return nil } diff --git a/internal/gen/genapi/routes.go b/internal/gen/genapi/routes.go index 1d1eaf56..14c4b625 100644 --- a/internal/gen/genapi/routes.go +++ b/internal/gen/genapi/routes.go @@ -8,6 +8,7 @@ import ( "go/printer" "go/token" "path/filepath" + "slices" "strings" "github.com/zeromicro/go-zero/tools/goctl/api/spec" @@ -87,6 +88,15 @@ func (ja *JzeroApi) genRoute2Code() ([]byte, error) { } } + slices.SortFunc(routes, func(a, b Route) int { + if a.Path < b.Path { + return -1 + } else if a.Path > b.Path { + return 1 + } + return 0 + }) + template, err := templatex.ParseTemplate(map[string]any{ "Routes": routes, }, embeded.ReadTemplateFile(filepath.Join("plugins", "api", "route2code.go.tpl")))