Handle url with parameters

blov · · 412 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Is there a mux that handles functions with extra parameters? I don&#39;t want to do the boilerplate code to convert MyHandler to http.Handler if I can avoid it. This code would probably be similar to how Spring Boot controllers and Django urldispatchers work. </p> <pre><code>package main import ( &#34;custom&#34; &#34;fmt&#34; ) type MyParam struct { Name string `param:&#34;name&#34;, loc:&#34;url&#34;` Date time.Time `param:&#34;date&#34;` Custom custom.Type `param:&#34;custom&#34; loc:&#34;query&#34;` // custom.Type implements something like encoding.TextUnmarshaler } func MyHandler(w http.ResponseWriter, r *http.Request, p MyParam) { } var mux MuxIamAskingFor func main() { fmt.Println(&#34;Hello, playground&#34;) mux.Handle(&#34;/asdf/(?P&lt;Name&gt;)/(?P&lt;Date&gt;)/&#34;, MyHandler) // With ?custom=parameter } </code></pre> <p>The server generator from goswagger generates code with the parameter as struct. Is there a net/http(ish) mux that does the same. Reflection and/or code generators would be acceptable. </p> <hr/>**评论:**<br/><br/>aboukirev: <pre><p>Here&#39;s a couple that stick to <code>net/http</code> standard but provide flexible routing. Both are quality libraries.</p> <p><a href="https://github.com/pressly/chi" rel="nofollow">https://github.com/pressly/chi</a></p> <p><a href="https://github.com/go-playground/pure" rel="nofollow">https://github.com/go-playground/pure</a></p></pre>hannson: <pre><p>I&#39;ve been using chi but a lot of my handlers share similar code just to convert parameters to their intended types. </p> <p>I&#39;m looking for a router that does that for me and gives me the params in a struct. </p></pre>metamatic: <pre><p><a href="https://github.com/codemodus/parth" rel="nofollow">parth</a> will probably handle your parameter conversion needs.</p></pre>dean_karn: <pre><p>if using <a href="https://github.com/go-playground/pure" rel="nofollow">https://github.com/go-playground/pure</a> (disclaimer I am author) it has a helper to decode these SEO params as I call them into a struct <a href="https://gist.github.com/joeybloggs/c610086166130d4f5d78ea082916b6c2" rel="nofollow">https://gist.github.com/joeybloggs/c610086166130d4f5d78ea082916b6c2</a></p> <p>Please note this will decode non-SEO query params as well such as ?id=13; I will be adding another helper today just to decode the SEO query params.</p></pre>

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

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