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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型