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