Hi,
I have a service that has this pattern for handlers. I am trying to add an API key checker and looking for ideas. I am aware of wrapping handerfunc but for that I need to do the refactor (there are 8 routes currently). Please help.
type handler struct {
Handler func(locator, http.ResponseWriter, *http.Request) error
l locator
}
func (h Handler) ServerHTTP(w http.ResponseWrtier, r *http.Request) {
err := h.handler(h.l, w, r)
//handle error
}
func getRouter(l locator) (*mux.Router, error) {
r := mux.NewRouter()
r.Path("/").Methods("GET").Handler(handler{foo, l})
r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, errBadHandlerRequest.Error(), http.StatusNotFound)
})
return r, nil
}
func foo(l locator, w http.ResponseWriter, r *http.Request) error {
results, err := getSomething(l.Service())
if err != nil {
return &HTTPError{http.StatusInternalServerError, err}
}
respondWith(w, http.StatusOK, results)
return nil
}