将参数传递给http.HandlerFunc [英] Passing in parameters to a http.HandlerFunc
问题描述
我使用内置于http服务器和 pat 的Go来响应某些网址:
mux.Get(/ products,http.HandlerFunc(index))
func index(w http.ResponseWriter,r * http.Request){
//做些什么。
}
我需要通过这个处理函数的一个额外参数 - 一个接口。
$ p $ func(api Api)Attach(resourceManager interface {},route string) {
//将典型的REST动作应用于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接口{}){
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)))
}
$ c $
您应该可以通过使用闭包来完成您的任务。 $ b
更改 func index()
到以下(未经测试):
func index(resourceManager接口{})http.HandlerFunc {
return func(w http.ResponseWriter,r * http.Request){
managerType:= string(reflect。 TypeOf(resourceManager).String())
w.Write([] byte(fmt.Sprintf(%v,managerType)))
}
}
然后对
I'm using Go's built in http server and pat to respond to some URLs:
mux.Get("/products", http.HandlerFunc(index))
func index(w http.ResponseWriter, r *http.Request) {
// Do something.
}
I need to pass in an extra parameter to this handler function - an 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)))
}
How can I send in an extra paramter to the handler function?
You should be able to do what you wish by using closures.
Change func index()
to the following (untested):
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)))
}
}
And then do the same to func show()
这篇关于将参数传递给http.HandlerFunc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!