gogorillanegroni

Negroni and Gorilla Context ClearHandler


Is is possible to use Gorilla's context.ClearHandler() as middleware for Negroni like I've seen it used as middleware for Alice? Something like:

n.Use(context.ClearHandler())

At the moment I'm calling context.Clear(r) after every response but I would prefer the tidying up to be taken care of automatically. I'm currently getting the following error:

cannot use context.ClearHandler() (type http.Handler) as type negroni.Handler in argument to n.Use:                                                                   
http.Handler does not implement negroni.Handler (wrong type for ServeHTTP method)                                                                                                  
  have ServeHTTP(http.ResponseWriter, *http.Request)                                                                                                                         
  want ServeHTTP(http.ResponseWriter, *http.Request, http.HandlerFunc)

But I'm not sure what the error message is telling me.


Solution

  • Negroni.Use() expects a parameter of type negroni.Handler but Gorilla's context.ClearHandler() returns a value of type http.Handler.

    Good thing is that there is an alternative Negroni.UseHandler() method which expects an http.Handler so just use that. Note that context.ClearHandler() also expects another http.Handler:

    otherHandler := ... // Other handler you want to clear
    n.UseHandler(context.ClearHandler(otherHandler))
    

    Notes:

    The Router from the gorilla/mux package automatically calls context.Clear() at the end of a request lifetime, so if you are using it you don't need to clear the context using context.ClearHandler(). You only need to use it for other / custom handlers (unless you want to call context.Clear() manually).