在Gorilla Mux中嵌套子路由器 [英] Nesting subrouters in Gorilla Mux

查看:104
本文介绍了在Gorilla Mux中嵌套子路由器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 gorilla/mux 来满足我的路由需求.但是我注意到一个问题,当我嵌套多个子路由器时,它不起作用.

I've been using gorilla/mux for my routing needs. But I noticed one problem, when I nest multiple Subrouters it doesn't work.

这里是示例:

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)

I wanted to use this approach so I can delegate populating the router to some other package, for example user.Populate(api)

但是,这似乎不起作用.仅当我在链中使用单个Subrouter时,它才有效.

However this doesn't seem to work. It works only if I use single Subrouter in the chain.

有什么想法吗?

推荐答案

我已经弄清楚了,所以我将其发布在这里,以防有人像我一样愚蠢.:D

I figured it out, so I'll just post it here in case someone is as stupid as I was. :D

创建基于路径的子路由器时,必须使用 PathPrefix 而不是 Path 来获取它.

When creating path-based subrouter, you have to obtain it with PathPrefix instead of Path.

r.PathPrefix("/api").Subrouter()

仅在将处理程序附加到该端点时才使用 r.Path("/api").

Use r.Path("/api") only when attaching handlers to that endpoint.

这篇关于在Gorilla Mux中嵌套子路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆