http - 将参数传递给 http.HandlerFunc

标签 http go handler

我正在使用 Go 的内置 http 服务器和 pat响应某些 URL:

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

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

我需要向这个处理函数传递一个额外的参数——一个接口(interface)。

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 - 将参数传递给 http.HandlerFunc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23773322/

相关文章:

去时间包常量而不是数字

javascript - 在 JavaScript 中不使用 DOM 事件的自定义事件模型

python - PyQt:如何在没有继承的情况下处理事件

Node.js 服务器处理请求回调函数在写入响应之前结束

.net - 如何获取 header 值

php - 处理缺少/错误键入的 GET 变量的最佳做法?

testing - Go,Golang : travis error for main program, go get -v

interface - 无法在非接口(interface)值上键入开关

javascript - 将事件处理程序添加到数组

http - Bing API HTTP 请求超时