I am trying to return a handler function from a Controller
In my controllers/item.go
file:
package controllers
import (
// ...
)
type Controller struct{}
func (c Controller) GetItems(db *sql.DB) http.Handler {
return http.Handler(func(w http.ResponseWriter, r *http.Request) {
// ...
})
}
In my main.go
file:
func main() {
db = db.Connect()
router := mux.NewRouter()
controllers := controllers.Controller{}
router.HandleFunc("/items", controllers.GetItems(db)).Methods("GET")
}
You can see I am using mux
. My problem is I have not been able to return the handler function. I keep getting this error:
cannot convert func literal (type func(http.ResponseWriter, *http.Request)) to type http.Handler:
func(http.ResponseWriter, *http.Request) does not implement http.Handler (missing ServeHTTP method)
You cannot arbitrarily convert a function to an http.Handler
, but the http
package does provide a convenient http.Handler
struct type, which satisfies the http.Handler
interface, and you can return an instance of this type easily:
func (c Controller) GetItems(db *sql.DB) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// ...
})
}
This actually works:
func (c Controller) GetItems(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
//...
}
}
I have changed the return type to http.HandlerFunc
and removed the wrapper from the returned function.