【问题标题】:Reversing a Subrouter in Gorilla / Mux在 Gorilla / Mux 中反转子路由器
【发布时间】:2015-01-28 12:36:17
【问题描述】:

我想获取命名子路由的路径,但下面的代码不起作用。当我尝试在非子路由上使用相同的逻辑时,它工作正常。如何获取命名子路由的路径?

router = mux.NewRouter() // this is a global variable
home := router.Path("/home").Subrouter()
home.Methods("GET").HandlerFunc(c.GetHomeHandler).Name("home")
home.Methods("POST").HandlerFunc(c.PostHomeHandler)

p, err := router.Get("home").URL()
if (err != nil) { panic (err) }
log.Printf(p.Path)

上面给出了这个错误:

panic: mux: route doesn't have a host or path

现在,如果我使用router.HandleFunc("/home", c.GetHomeHandler).Name("home"),它就可以正常工作。

感谢您的帮助。

更新:

这是一个合理的解决方法,但它避免了创建子路由。这对我上面的例子来说很好,但可能并不理想,因为你不会得到子路由的所有好处。

router.Path("/home").Methods("GET").HandlerFunc(c.GetHomeHandler).Name("home")
router.Path("/home").Methods("POST").HandlerFunc(c.PostHomeHandler)

谢谢!

【问题讨论】:

    标签: go gorilla


    【解决方案1】:

    我相信您需要使用 PathPrefix 指定您的子路由,然后才能支持 /home 和 /home/ 启用 StrictSlash (due to this issue)

    router := mux.NewRouter() 
    home := router.PathPrefix("/home").Subrouter().StrictSlash(true)
    home.Path("/").Methods("GET").HandlerFunc(GetHomeHandler).Name("home")
    home.Path("/post/").Methods("POST").HandlerFunc(PostHomeHandler).Name("home-post")
    
    
    p, err := router.Get("home").URL()
    if (err != nil) { panic (err) }
    log.Printf(p.Path)
    
    p, err = home.Get("home-post").URL()
    if (err != nil) { panic (err) }
    log.Printf(p.Path)
    

    【讨论】:

    • 谢谢@John。看起来 API 已更改为 home.Path 返回 Route 类型并且它没有 StrictSlash 方法。我已经用解决方法更新了我的答案,但它不使用子路由。
    • 您遇到的问题是由于在定义家庭子路由器时没有使用 PathPrefix
    • 谢谢,这行得通!您必须在末尾添加StrictSlash(true)(您的代码没有输入参数true)。能否请您在有机会时对其进行更新,使其功能齐全?
    猜你喜欢
    • 2014-09-08
    • 2016-04-07
    • 2015-06-17
    • 1970-01-01
    • 2015-04-05
    • 2017-11-07
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    相关资源
    最近更新 更多