小编典典

将参数传递给http.HandlerFunc

go

我正在使用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)))
}

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


阅读 244

收藏
2020-07-02

共1个答案

小编典典

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

更改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()

2020-07-02