6
我使用Go的內置的HTTP服務器和pat迴應一些網址:在參數傳遞到http.HandlerFunc
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)))
}
如何發送額外的參數給處理函數?
偉大的思想思想一樣!我會刪除我的答案。 :) – sergserg
呵呵,是的,我看到你自己的結論中有__exact__相同的代碼。 – ANisus
另一個簽名:'func index(rm interface {})http.HandlerFunc {return func(w http.ResponseWriter,r * http.Request){...}}' – elithrar