英文:
In Go gin framework , how to get all url that I have registered in the router
问题
我正在使用Casbin编写基于角色的访问控制。然而,警察需要我提供角色拥有的URL。请看表格中的“v1”列,见图片。
我想知道是否可以获取我在路由器中注册的所有URL,这样我就不需要手动添加了。
英文:
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.
答案1
得分: 1
你可以使用Routes
方法,它会返回一个RoutesInfo
的切片,通过它你可以获取所有注册的路由路径以及其他额外的信息。
RoutesInfo
结构体包含以下字段,可以从中获取所需的信息。
type RouteInfo struct {
Method string
Path string
Handler string
HandlerFunc HandlerFunc
}
r := gin.Default()
r.Routes()
英文:
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()
答案2
得分: 0
*gin.Engine.Routes()
确实提供了端点信息,但它的返回值有些奇怪,它返回的是另一个结构体,实际上包含了RouteInfo
的切片,但没有s
。RouteInfos
才是.Routes()
实际返回的内容。
在我的用例中,我想在/
端点中显示端点信息以便于检查。以下是我的代码:
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())))
}
})
英文:
*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()) ))
}
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论