在 Gorilla Mux 中嵌套子路由器
Posted
技术标签:
【中文标题】在 Gorilla Mux 中嵌套子路由器【英文标题】:Nesting subrouters in Gorilla Mux 【发布时间】:2015-06-17 00:44:25 【问题描述】:我一直在使用gorilla/mux
来满足我的路由需求。但是我注意到一个问题,当我嵌套多个子路由器时它不起作用。
示例如下:
func main()
r := mux.NewRouter().StrictSlash(true)
api := r.Path("/api").Subrouter()
u := api.Path("/user").Subrouter()
u.Methods("GET").HandleFunc(UserHandler)
http.ListenAndServe(":8080", r)
我想使用这种方法,以便我可以将填充路由器委托给其他包,例如user.Populate(api)
但是这似乎不起作用。仅当我在链中使用单个子路由器时它才有效。
有什么想法吗?
【问题讨论】:
【参考方案1】:我想通了,所以我就把它贴在这里,以防有人像我一样愚蠢。 :D
在创建基于路径的子路由器时,您必须使用PathPrefix
而不是Path
来获取它。
r.PathPrefix("/api").Subrouter()
仅在将处理程序附加到该端点时使用r.Path("/api")
。
【讨论】:
【参考方案2】:对于那些难以在 auth 和 noauth 路由之间进行区分的人,以下方法对我来说很好:
r := mux.NewRouter()
noAuthRouter := r.MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool
return r.Header.Get("Authorization") == ""
).Subrouter()
authRouter := r.MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool
return true
).Subrouter()
那么你可以只为authRouter应用中间件
【讨论】:
【参考方案3】:如果您需要分离 UI 和 API 路由器,您可以简单地按照 OP 的建议进行操作:
appRouter := r.PathPrefix("/").Subrouter()
appRouter.Use(myAppRouter)
apiRouter := r.PathPrefix("/api").Subrouter()
apiRouter.Use(myAPIRouter)
非常感谢 OP 提供答案。希望为我的用例将所有内容集中在一个地方会对某人有所帮助。
【讨论】:
以上是关于在 Gorilla Mux 中嵌套子路由器的主要内容,如果未能解决你的问题,请参考以下文章
GolangWeb 入门 08 集成 Gorilla Mux
GolangWeb 入门 08 集成 Gorilla Mux