gonegroni

Can I use my function as `negroni` middleware


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 ?


Solution

  • The hurdle you'll have to cross with using your WrapHandler as negroni middleware is that your WrapHandler is actually an adaptor, not a wrapper. You're taking a non-http.HandlerFunc and converting it to a http.HandlerFunc.

    I can't think of a way to do that in middleware, because middleware just acts on the request/response and the http.HandlerFunc(s).