Handle url with parameters

blov · 2017-04-20 22:00:02 · 604 次点击    
这是一个分享于 2017-04-20 22:00:02 的资源,其中的信息可能已经有所发展或是发生改变。

Is there a mux that handles functions with extra parameters? I don'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.

package main

import (
    "custom"
    "fmt"
)

type MyParam struct {
    Name   string      `param:"name", loc:"url"`
    Date   time.Time   `param:"date"`
    Custom custom.Type `param:"custom" loc:"query"` // custom.Type implements something like encoding.TextUnmarshaler 
}

func MyHandler(w http.ResponseWriter, r *http.Request, p MyParam) {

}

var mux MuxIamAskingFor

func main() {
        fmt.Println("Hello, playground")
        mux.Handle("/asdf/(?P<Name>)/(?P<Date>)/", MyHandler) // With ?custom=parameter

}

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.


评论:

aboukirev:

Here's a couple that stick to net/http standard but provide flexible routing. Both are quality libraries.

https://github.com/pressly/chi

https://github.com/go-playground/pure

hannson:

I've been using chi but a lot of my handlers share similar code just to convert parameters to their intended types.

I'm looking for a router that does that for me and gives me the params in a struct.

metamatic:

parth will probably handle your parameter conversion needs.

dean_karn:

if using https://github.com/go-playground/pure (disclaimer I am author) it has a helper to decode these SEO params as I call them into a struct https://gist.github.com/joeybloggs/c610086166130d4f5d78ea082916b6c2

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.


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

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