In Gorilla Mux, by default, handlers receive only http.ResponseWriter and *http.Request. However, there are scenarios where passing additional arguments to handlers is necessary, such as a database connection object.
One way to achieve this is to define a custom type that holds the additional data and implements the http.HandlerFunc interface.
type UserHandler struct { db *gorm.DB } func (h UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // here you can use db } // usage: db := createDB() users := UserHandler{db: db} router.HandleFunc("/users/{id}", users.ServeHTTP)
Another option is to use a closure function to wrap the actual handler and inject the additional argument.
func showUserHandler(db *gorm.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // here you can use db } } // usage: db := createDB() router.HandleFunc("/users/{id}", showUserHandler(db))
In certain scenarios, using global variables may be acceptable, especially for shared resources like database connections. However, it's important to use them sparingly and understand the potential drawbacks.
var db *gorm.DB = createDB() func showUserHandler(w http.ResponseWriter, r *http.Request) { // here you can use db } // usage: router.HandleFunc("/users/{id}", showUserHandler)
The above is the detailed content of How to Pass Additional Arguments to Handler Functions in Gorilla Mux?. For more information, please follow other related articles on the PHP Chinese website!