Skip to content

Commit

Permalink
fix(gen): fix gen route2code
Browse files Browse the repository at this point in the history
fix(gen): fix gen route2code
  • Loading branch information
jaronnie committed Nov 28, 2024
1 parent bedcd21 commit 7e008e7
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
14 changes: 10 additions & 4 deletions .template/plugins/api/route2code.go.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
package handler

import (
"fmt"
"net/http"
"strings"

casbinutil "github.com/casbin/casbin/v2/util"
)

var routesCodesMap = map[string]string{
Expand All @@ -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"
}
2 changes: 2 additions & 0 deletions internal/gen/genapi/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -286,13 +286,15 @@ 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 {
if err = os.WriteFile(filepath.Join("internal", "handler", "route2code.go"), route2CodeBytes, 0o644); err != nil {
return err
}
}
fmt.Printf("%s", color.WithColor("Done\n", color.FgGreen))
}
return nil
}
10 changes: 10 additions & 0 deletions internal/gen/genapi/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"go/printer"
"go/token"
"path/filepath"
"slices"
"strings"

"github.com/zeromicro/go-zero/tools/goctl/api/spec"
Expand Down Expand Up @@ -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")))
Expand Down

0 comments on commit 7e008e7

Please sign in to comment.