Timeout-Context-In-Go
Go ahead , make my day.
In concurrent programming with Golang, the context package is a powerful tool to manage operations like timeouts, cancelation, deadlines, etc.
Among these operations, context with timeout is mainly used when we want to make an external request, such as a network request or a database request. I will show you how to use it to timeout a goroutine in this post.
Let’s first see a simple example.
1 | package main |
Okay, what are we doing here?
1. Timeout Context
Creating a timeout context is very easy. We use the function WithTimeout from the context package.
The following example defines a timeout context that will be canceled after 3 seconds.
1 | ctxTimeout, cancel := context.WithTimeout(context.Background(), time.Second*3) |
Here, the WithTimeout takes a parent context and a duration parameter and returns a child context with a deadline set to the specified duration.
The parent context is returned by function Background. It is a non-nil, empty Context and is typically used by the main function as the top-level Context for incoming requests.
2. Long Waiting Function
We define a function that will execute in a separate goroutine. It will send the result to a predefined channel when finished.
1 | func doSomething(ctx context.Context, ch chan string) { |
The following is the predefined buffered channel.
1 | ch := make(chan string, 1) |
How to execute this function? It’s easy!
1 | go doSomething(ctxTimeout, ch) |
3. Waiting Orchestration
We wait for the result from the predefined result or from the timeout context channel in the main function.
The context will automatically signal to the ctxTimeout.Done
channel if the timeout is reached. Otherwise, we will receive the result from the ch channel.
1 | select { |
User Cases
To better understand the context, let’s look at some real-world use cases.
Mongo
1 | opts := options.Client() |
http.Get() timeout per request
1 | ctx, cancel := context.WithTimeout(context.Background(), time.Microsecond*200) |
https://medium.com/geekculture/timeout-context-in-go-e88af0abd08d