douzhuiqing1151 2015-01-24 02:25
浏览 39
已采纳

反转大猩猩/多路复用器中的子路由器

I would like to get the path for a named subroute but my code below does not work. When I try to use the same logic on a non-subroute, it works fine. How do I get the path of a named subroute?

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)

The above gives this error:

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

Now if I do router.HandleFunc("/home", c.GetHomeHandler).Name("home"), it works just fine.

Appreciate your help.

Update:

This is a reasonable workaround but it avoids creating a Subroute. It is fine for the example I had above but probably not ideal as you will not get all the benefits of a Subroute.

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

Thanks!

  • 写回答

1条回答 默认 最新

  • duanpanbo9476 2015-01-24 04:48
    关注

    I believe you'd need to specify your subroute with a PathPrefix, then in order to support /home and /home/ enable 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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi