如何在Go中从mux获取可用的路由?

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

How to get available routes from the mux in go?

问题

我有一个 mux 和 4 条不同的路由。

a.Router = mux.NewRouter()

a.Router.HandleFunc("/1/query/{query}", a.sigQuery).Methods("GET")

a.Router.HandleFunc("/1/sis", a.rGet).Methods("GET")

a.Router.HandleFunc("/1/sigs", a.sigHandler).Methods("GET", "POST", "DELETE")

a.Router.HandleFunc("/1/nfeeds", a.nfeedGet).Methods("GET", "DELETE", "POST")

有没有一种方法可以列出定义的路由并获取它们上定义的方法?我尝试了这种方式:routes := a.getRoutes() 将返回一个包含所有路由的切片,methods := routes[1].Methods() 将返回该路由上列出的方法。我们有办法实现这个吗?

英文:

I have a mux and 4 different routes.

a.Router = mux.NewRouter()

a.Router.HandleFunc("/1/query/{query}", a.sigQuery).Methods("GET")

a.Router.HandleFunc("/1/sis", a.rGet).Methods("GET")

a.Router.HandleFunc("/1/sigs", a.sigHandler).Methods("GET", "POST", "DELETE")

a.Router.HandleFunc("/1/nfeeds", a.nfeedGet).Methods("GET", "DELETE", "POST")

Is there a method where we can list the defined routes and get the methods defined on them. I was trying this way: routes := a.getRoutes() will return me a slice with all the routes, and methods := routes[1].Methods() will return the methods listed on that route. Is there a way we can achieve this?

答案1

得分: 10

使用Walk方法:

router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
	tpl, err1 := route.GetPathTemplate()
	met, err2 := route.GetMethods()
	fmt.Println(tpl, err1, met, err2)
	return nil
})

或者,您可以将所有路由放入一个结构体切片中,然后在初始化步骤中执行以下操作:

for _, r := range routes {
    router.HandleFunc(r.tpl, r.func).Methods(r.methods...)
}
英文:

Use the Walk method:

router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
	tpl, err1 := route.GetPathTemplate()
	met, err2 := route.GetMethods()
	fmt.Println(tpl, err1, met, err2)
	return nil
})

Alternatively, you can just put all your routes into a slice of structs and just do

for _, r := range routes {
    router.HandleFunc(r.tpl, r.func).Methods(r.methods...)
}

on the initialisation step.

huangapple
  • 本文由 发表于 2017年7月7日 00:44:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/44954705.html
匿名

发表评论

匿名网友

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

确定