I have a function which I use as wrapper for every GET request:
type HandlerFunc func(w http.ResponseWriter, req *http.Request) (interface{}, error)
func WrapHandler(handler HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
data, err := handler(w, req)
if err != nil {
log.Println(err)
w.WriteHeader(500)
} else {
w.Header().Add("Content-Type", "application/json")
resp, _ := json.Marshal(data)
w.Write(resp)
}
}
}
router:
router.HandleFunc("/rss/unread/{rss_type}",
controllers.WrapHandler(controllers.GetUnreadRssFeeds))
example:
func GetUnreadRssFeeds(w http.ResponseWriter, r *http.Request) (interface{}, error) {
vars := mux.Vars(r)
rss_type, err := strconv.Atoi(vars["rss_type"])
feeds, err := (&postgres.FeedService{}).GetUnreadRssFeeds(rss_type)
return feeds, err
}
Now I need wrap each request in the router: controllers.WrapHandler(controllers.GetUnreadRssFeeds)
. I am looking the way to avoid it.
Can I transform my WrapHandler
to use it as negroni
middleware ? Is there a way to pass data between negroni
middleware functions ?