In Go gin framework , how to get all url that I have registered in the router

2.9k Views Asked by At

I’m programming the role based access control with casbin. However ,the police need me to provide urls that the role has. The “v1” column in the table, see the picture. I wondered can I get all urls that I registered in router. So that I don’t need to add by my hand.

2

There are 2 best solutions below

0
Chandan On

You can use Routes which would return slice of RoutesInfo through which you can get all the register route path plus additional informaiton.

RoutesInfo will contain below struct from which required information can be retrieved.

type RouteInfo struct {
    Method      string
    Path        string
    Handler     string
    HandlerFunc HandlerFunc
}
r := gin.Default()
r.Routes()
0
rminaj On

*gin.Engine.Routes() does give the endpoints, but is quite weird because it returns another struct which is what actually contain the slice of RouteInfo, without the s. RouteInfos is what .Routes() actually returns.

In my use-case, I wanted to display the endpoints in the / endpoint for easy checking. Here's my code for that:

ginGine.GET("/", func(ctx *gin.Context) {
    if gin.Mode() == gin.DebugMode {
        ctx.Data(200, "application/json; charset=utf-8", []byte( fmt.Sprintf("%v", ginGine.Routes()) ))
    }
})