グローバル オブジェクトではなく、データベース オブジェクトをハンドラーに渡そうとしています。しかし、これが可能かどうかはわかりません.Gorilla Muxパッケージを使用しています.2番目のパラメータとしてクロージャが必要であることがわかります.
// 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)
}
次に、使用できるパラメーターを定義します。理想的には、このような3番目のパラメーターが必要です。
// In my main
router.HandleFunc("/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"])
}
回避策はありますか? または、グローバル db オブジェクトが必要ですか? Go は初めてなので、考えられる答えを詳しく説明してください。