In this post, we will implement a function that uses context. In the calling example, I will use the WithTimeout context. In this way, we will be able to make the function be canceled automatically, in case its execution time exceeds the time stipulated in the context.
Let’s start by creating a function named doSomeHeavyWork.
To simulate lengthy processing, let’s add a goroutine with a 2-second sleep. This goroutine will receive a channel of type bool. It will signal that the goroutine is finished.
In the struct context.Context, we have a method called Done(). This method returns a channel. When the context is finished, that channel will be closed, and this method returns a channel. This will occur when:
-> WithCancel – when the cancel function is executed;
-> WithDeadline – when the deadline expires;
-> WithTimeout – when timeout is reached.
As we have a control channel for sleep and another for context, we need to add a select to capture the activated channel.
To test our function, let’s create a context with a timeout of 1 second.
When running the program with a gorun main.go, we will have the following result:
Changing the time of our timeout to 3 seconds and running the program again, the result will be, the message work completed!
If you want to know a little more about the types of content available and when they are normally used, I recommend reading our post “Where and which context to use”.
Hope this helps, and until next time!
*The content of this article is the author’s responsibility and does not necessarily reflect the opinion of iMasters.
Leave a comment