Created
June 11, 2017 15:25
-
-
Save AndreKR/858fc4edddf2ecfd78f1986939ed6cac to your computer and use it in GitHub Desktop.
Go http + context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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