Nested subrouters with gorilla mux

agolangf · · 872 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;ve been using gorilla/mux for my routing needs. But I noticed one problem, when I nest multiple Subrouters it doesn&#39;t work.</p> <p>Here is the example:</p> <pre><code>func main() { r := mux.NewRouter().StrictSlash(true) api := r.Path(&#34;/api&#34;).Subrouter() u := api.Path(&#34;/user&#34;).Subrouter() u.Methods(&#34;GET&#34;).HandlerFunc(UserHandler) http.ListenAndServe(&#34;:8080&#34;, r) } </code></pre> <p>I wanted to use this approach so I can delegate populating the router to some other package, for example user.Populate(api)</p> <p>However this doesn&#39;t seem to work. It works only if I use single Subrouter in the chain.</p> <p>Any ideas?</p> <hr/>**评论:**<br/><br/>kortemy: <pre><p>I figured it out, so I&#39;ll just post it here in case someone is as stupid as I was. :D</p> <p>When creating path-based subrouter, you have to obtain it with PathPrefix instead of Path.</p> <pre><code>r.PathPrefix(&#34;/api&#34;).Subrouter() </code></pre> <p>Use r.Path(&#34;/api&#34;) only when attaching handlers to that endpoint.</p></pre>dreadyfire: <pre><p>Would you mind posting this question/answer over on stackoverflow.com too?</p></pre>kortemy: <pre><p>I did. <a href="http://stackoverflow.com/questions/29575972/nesting-subrouters-in-gorilla" rel="nofollow">http://stackoverflow.com/questions/29575972/nesting-subrouters-in-gorilla</a></p></pre>dreadyfire: <pre><p>Thank you very much</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

872 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传