<p>I've been using gorilla/mux for my routing needs. But I noticed one problem, when I nest multiple Subrouters it doesn't work.</p>
<p>Here is the example:</p>
<pre><code>func main() {
r := mux.NewRouter().StrictSlash(true)
api := r.Path("/api").Subrouter()
u := api.Path("/user").Subrouter()
u.Methods("GET").HandlerFunc(UserHandler)
http.ListenAndServe(":8080", 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'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'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("/api").Subrouter()
</code></pre>
<p>Use r.Path("/api") 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
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传