繁体   English   中英

将参数传递给http.HandlerFunc

[英]Passing in parameters to a http.HandlerFunc

我正在使用Go内置的http服务器,并拍拍来响应一些URL:

mux.Get("/products", http.HandlerFunc(index))

func index(w http.ResponseWriter, r *http.Request) {
    // Do something.
}

我需要向该处理函数传递一个额外的参数-一个接口。

func (api Api) Attach(resourceManager interface{}, route string) {
    // Apply typical REST actions to Mux.
    // ie: Product - to /products
    mux.Get(route, http.HandlerFunc(index(resourceManager)))

    // ie: Product ID: 1 - to /products/1
    mux.Get(route+"/:id", http.HandlerFunc(show(resourceManager)))
}

func index(w http.ResponseWriter, r *http.Request, resourceManager interface{}) {
    managerType := string(reflect.TypeOf(resourceManager).String())
    w.Write([]byte(fmt.Sprintf("%v", managerType)))
}

func show(w http.ResponseWriter, r *http.Request, resourceManager interface{}) {
    managerType := string(reflect.TypeOf(resourceManager).String())
    w.Write([]byte(fmt.Sprintf("%v", managerType)))
}

如何向处理程序函数发送额外的参数?

通过使用闭包,您应该能够做您想做的事情。

func index()更改为以下(未调试):

func index(resourceManager interface{}) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        managerType := string(reflect.TypeOf(resourceManager).String())
        w.Write([]byte(fmt.Sprintf("%v", managerType)))
    }
}

然后对func show()做同样的事情

另一种选择是使用直接实现http.Handler类型,而不是仅使用函数。 例如:

type IndexHandler struct {
    resourceManager interface{}
}

func (ih IndexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    managerType := string(reflect.TypeOf(ih.resourceManager).String())
    w.Write([]byte(fmt.Sprintf("%v", managerType)))
}

...
mux.Get(route, IndexHandler{resourceManager})

如果要将ServeHTTP处理程序方法重构为多个方法,则这种模式很有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM