将参数传递给http.HandlerFunc

ser*_*erg 8 http handler go

我正在使用Go内置的http服务器并轻拍以响应某些网址:

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

func index(w http.ResponseWriter, r *http.Request) {
    // Do something.
}
Run Code Online (Sandbox Code Playgroud)

我需要将一个额外的参数传递给这个处理函数 - 一个接口.

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)))
}
Run Code Online (Sandbox Code Playgroud)

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

ANi*_*sus 14

你应该能够通过使用闭包来做你想做的事.

更改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)))
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Jam*_*dge 8

另一种选择是使用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})
Run Code Online (Sandbox Code Playgroud)

如果要将ServeHTTP处理程序方法重构为多个方法,则此类模式非常有用.