2

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.

icza
  • 389,944
  • 63
  • 907
  • 827
tommyd456
  • 10,443
  • 26
  • 89
  • 163

1 Answers1

4

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).

icza
  • 389,944
  • 63
  • 907
  • 827
  • Thanks but getting: `not enough arguments in call to context.ClearHandler` – tommyd456 May 28 '15 at 12:51
  • @tommyd456 Yes, updated the answer. `context.ClearHandler()` also expects another `http.Handler`. – icza May 28 '15 at 12:53
  • So I can do away with my `n.UseHandler(router)` and simply add `n.UseHandler(context.ClearHandler(router))` ? – tommyd456 May 28 '15 at 12:56
  • @tommyd456 Please see edited answer. If you are using `mux.Router`, that automatically clears at the end of requests lifetime, so you don't need to use `context.ClearHandler()` at all. You only need to use it for other/custom handlers (unless you want to call `context.Clear()` manually). – icza May 28 '15 at 14:37
  • I should have mentioned - I'm using httprouter by Julien Schmidt – tommyd456 May 28 '15 at 15:33