Introduction
This challenge aims to demonstrate the usage of context.Context
for controlling cancellation in Golang. A Context
carries deadlines, cancellation signals, and other request-scoped values across API boundaries and goroutines.
This tutorial is from open-source community. Access the source code
This challenge aims to demonstrate the usage of context.Context
for controlling cancellation in Golang. A Context
carries deadlines, cancellation signals, and other request-scoped values across API boundaries and goroutines.
The hello
function simulates some work the server is doing by waiting for a few seconds before sending a reply to the client. While working, keep an eye on the context's Done()
channel for a signal that we should cancel the work and return as soon as possible.
## Run the server in the background.
$ go run context-in-http-servers.go &
## Simulate a client request to `/hello`, hitting
## Ctrl+C shortly after starting to signal
## cancellation.
$ curl localhost:8090/hello
server: hello handler started
^C
server: context canceled
server: hello handler ended
In this challenge, we learned how to use context.Context
to control cancellation in Golang. By creating a Context
with a timeout and passing it to a function, we can ensure that the function returns as soon as possible if the timeout is exceeded.