I am trying to pass my database object along to my handlers, instead of having a global object. But I don\'t know if this is possible, I\'m using Gorilla Mux package, and I can
Welcome to Go.
It is acceptable to have global variables and specially database objects.
However, there are few ways to workaround that if you prefer not to, for example you can create a struct and define your showHandler
on it.
type Users struct {
db *gorm.DB
}
func (users *Users) showHandler(w http.ResponseWriter, r *http.Request) {
//now you can use users.db
}
func (users *Users) addHandler(w http.ResponseWriter, r *http.Request) {
//now you can use users.db
}
// setup
users := &Users{db: createDB()}
router.HandleFunc("/users/{id}", users.showHandler).Methods("GET")
router.HandleFunc("/users/new", users.addHandler)
//etc
Another approach is creating a wrapper function:
db := createDB()
router.HandleFunc("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
showUserHandler(w, r, db)
}).Method("GET")