Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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