I'm trying to make an interface similar to http.Handler
. For certain endpoints of my API I need a APNS token included in the query or I need to respond with http.StatusBadRequest
.
I want the type DeviceHandlerFunc
to implement ServeHTTP(http.ResponseWriter, *http.Request)
and automatically parse the token and call itself with the token:
type DeviceHandlerFunc func(http.ResponseWriter, *http.Request, string)
func (f DeviceHandlerFunc) ServeHTTP(res http.ResponseWriter, req *http.Request) {
token := req.URL.Query().Get("token")
if token == "" {
http.Error(res, "token missing from query", http.StatusBadRequest)
} else {
f(res, req, token)
}
}
Then from main.go
:
func main() {
mux := http.NewServeMux()
mux.Handle("/", getDevice)
log.Fatal(http.ListenAndServe(":8081", mux))
}
func getDevice(res http.ResponseWriter, req *http.Request, token string) {
// Do stuff with token...
}
This causes a compiler error:
main.go:22:13: cannot use getDevice (type func(http.ResponseWriter, *http.Request, string)) as type http.Handler in argument to mux.Handle:
func(http.ResponseWriter, *http.Request, string) does not implement http.Handler (missing ServeHTTP method)
In my mind I couldn't be more clear that the type func(http.ResponseWriter, *http.Request, string)
implements http.Handler
. What am I doing wrong?
Sample code as playground.