The Simplest Way to Handle Timeouts in Golang

Arindam Roy
The Startup
Published in
4 min readAug 15, 2019

--

Source: http://www.quickmeme.com

For any real life application that does any tasks that are resource-intensive, timeouts are a necessary evil. Timeouts are necessary to have checks and balances to ensure that tasks that run overdue do not consume necessary resources or network bandwidth that might be needed by other components of our application.

With Golang, the approach to handling this has become as simple as it gets. Without using any complicated code, we can handle timeouts by using channels for communication and the select statement for timeout decisions.

For more details on the above features, you read the Golang documentation here.

So let’s get started.

First, the basics. To simulate a network activity, we will read the response from a mock service, provided by typicode.

We write a quick struct to read the response from this service.

Pretty straight forward. Now we will just write a quick method to fetch the response from our mock service, and return it back to the caller.

--

--

Arindam Roy
The Startup

Product @hyperverge. I write about a lot of things, mostly tech.