我想將我的數據庫對象傳遞給我的處理程序,而不是具有全局對象。但我不知道這是否可行,我使用的是Gorilla Mux軟件包,而且我可以看到它需要一個閉包作爲第二個參數。如何將參數傳遞給我的處理程序
// https://github.com/gorilla/mux/blob/master/mux.go#L174
// HandleFunc registers a new route with a matcher for the URL path.
// See Route.Path() and Route.HandlerFunc().
func (r *Router) HandleFunc(path string, f func(http.ResponseWriter,
*http.Request)) *Route {
return r.NewRoute().Path(path).HandlerFunc(f)
}
然後,它定義了我可以使用的參數,理想情況下,我想有這樣的第三個參數。
// In my main
router.HandleFunc("https://stackoverflow.com/users/{id}", showUserHandler).Methods("GET")
func showUserHandler(w http.ResponseWriter, r *http.Request, db *gorm.DB) {
fmt.Fprintf(w, "We should fetch the user with id %s", vars["id"])
}
是否有解決方法?或者我需要一個全局數據庫對象?我是Go的新手,所以請詳細解釋一下可能的答案。
http://stackoverflow.com/a/26106655/6309可以給你一些想法了。 – VonC 2014-10-06 08:12:51
@VonC我實際上嘗試http://simonsdotnet.wordpress.com/2014/09/06/extending-gos-http-handlers/,但發現它沒有與大猩猩一起工作,因爲http包只是想要ServeHTTP,但大猩猩想要一個具有特定參數的函數。我可能是錯的。 – MartinElvar 2014-10-06 08:18:28