3 ms·
How is this Context supposed to work with middleware packages that build on the standard Go http interface? Seems to me that you have to declare Context as a pa
by mg74 12y ago
How is this Context supposed to work with middleware packages that build on the standard Go http interface? Seems to me that you have to declare Context as a parameter to your functions t o use it. Am I misreading something?
- 2mur 12y agoProbably something like: // h already has a context.Context in scope through similar func MyHandler (ctx context.Context, h http.Handler) http.Handler { return http.HandlerFunc(func (rw http.ResponseWriter, req *http.Request) { // do stuff before handler h.serveHttp(rw, req) // do stuff after handler }) } then you can just chain your handlers and pass through a shared context
- carbocation 12y agoIn Interpose, that's exactly the pattern I use to pull in methods that require context while still satisfying the http.Handler interface (e.g., https://github.com/carbocation/interpose/blob/master/examples/menagerie/ascendinginteger.go https://github.com/carbocation/interpose/blob/master/example... ), so it seems that this pattern would work well with Google's Context.
- nkozyra 12y agoBased on a cursory glance I'd say those middleware packages could also use that unless they've rebuilt net/http entirely. Some of the examples demonstrate that.
- Sajmani 12y agoIn Google, we use two approaches: 1) add an explicit Context parameter to each function that needs one; typically this is the first parameter and is named "ctx". This makes it obvious how to cancel that function and pass stuff through it, but it's a lot of work. We are developing static analysis and refactoring tools to help automate tasks like this. 2) use a package to map http.Requests to Contexts. This requires that whatever server handler you're using register a Context in a map for each http.Request and remove it when the request completes. You could do this using the gorilla context package, for example. My personal preference is the explicit ctx parameter, since then libraries are agnostic to the framework being used. Different frameworks can provide their own Context implementations; middleware should not care.