在Go Gin框架中,如何获取我在路由器中注册的所有URL?

huangapple go评论69阅读模式
英文:

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的切片,但没有sRouteInfos才是.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()) ))
	}
})

huangapple
  • 本文由 发表于 2022年5月13日 12:19:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/72224396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定