Timeout Context In Go

Jerry An
Geek Culture
Published in
2 min readMay 5, 2022

--

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.

Timeout Context Example

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.

Here, the WithTimeout takes a parent context and a duration parameter and returns a child context…

--

--

Responses (3)