Skip to content

Instantly share code, notes, and snippets.

@AndreKR
Created June 11, 2017 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreKR/858fc4edddf2ecfd78f1986939ed6cac to your computer and use it in GitHub Desktop.
Save AndreKR/858fc4edddf2ecfd78f1986939ed6cac to your computer and use it in GitHub Desktop.
Go http + context
// While the Go documentation promotes the context package for keeping track of request context and cancelation, to
// actually use it for canceling work in http requests some plumbing is necessary:
// getCancelableContextFromResponseWriter gets a context.Context that is canceled when the client (browser) closes the connection
func getCancelableContextFromResponseWriter(w http.ResponseWriter) context.Context {
// Create a context that can be handed down to the workers to relay cancellation
ctx, cancelContext := context.WithCancel(context.Background())
// Get a channel that receives a value when the request is canceled
cn := w.(http.CloseNotifier)
cc := cn.CloseNotify()
// Connect the channel to the cancel function
go func() {
<-cc
cancelContext()
}()
return ctx
}
// contextIsCanceled returns true if the Context ctx is canceled
func contextIsCanceled(ctx context.Context) bool {
select {
case <-ctx.Done():
// There is never anything written to the channel, but when the channel is closed, this case will also be
// chosen, so if we are here the channel must have been closed
return true
default:
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment