I want to add a name to the gin route because I need to collect all the routes and display them on the page. route.go
func main() {
r := gin.Default()
r.GET("/api/user/list", handler1)
r.POST("/api/user/create",handle2)
r.Run()
}
This is the structure I need to collect:
var Routes []Route
type Route struct {
Name string `json:"name"`
Sign string `json:"sign"`
HttpMethod string `json:"http_method"`
HttpPath string `json:"http_path"`
}
What have I tried?
1.This is not an automatic method and requires manual maintenance of route names.
var RouteNameMap = map[string]string{
"api.user.list":"Get User List",
"api.user.create": "Create an User"
}
func ParseRoutes(r *gin.Engine, group string) {
routes := r.Routes()
for _, route := range routes {
if strings.HasPrefix(route.Path, group) {
sign := strings.Replace(strings.Trim(route.Path, "/"), "/", ".", -1)
item := Route{
Name: RouteNameMap[sign],
Sign: sign,
HttpMethod: route.Method,
HttpPath: route.Path,
}
Routes = append(Routes, item)
}
}
}
3.Similar to the first method:
func main() {
r := gin.Default()
MyGET(r,"/api/user/list", handler1,"Get User List")
MyPOST(r,"/api/user/create",handle2,"Create an User")
r.Run()
}
func MyPOST(engine *gin.Engine, path string, handlerFunc gin.HandlerFunc, name string) {
engine.POST(path, handlerFunc)
Routes = append(Routes, Route{
Name: name,
Sign: strings.Replace(strings.Trim(path, "/"), "/", ".", -1),
HttpMethod: "POST",
HttpPath: path,
})
}
output:
[{
"name": "Get User List",
"sign": "api.user.list",
"http_method": "GET",
"http_path": "/api/user/list"
},
{
"name": "Create an User",
"sign": "api.user.create",
"http_method": "post",
"http_path": "/api/user/create"
}
]
But I feel that this method is not in line with the standards.I hope to add a similar name parameter to gin's POST and GET methods. And this name parameter can be parsed in the ParseRoutes method, what should I do? Thanks
So, what's wrong with the third method?
If the Route of the Gin framework does not provide parameters to set the Name, then you can only do this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With