Go Context Explained

Sundara Senthil
5 min readNov 16, 2020

--

Written by Sundara Senthil and Edited by Angelica Hill

Welcome everyone to my first technical blog!

This blog has been written for beginners to Go Lang and the use of Context Packages in Go. However, I hope it will be of interest to Gophers of all levels

This blog will go through what context is, why it’s used, as well as going through a few examples of how the Context package can be used in Go. I will then give you an outline of the Rules of Use, before summarizing.

What is Context?

If your main task is to make a shirt, first you need to complete a few sub-tasks, such as buying the material, thread, buying buttons, as well as designing what you want your shirt to look like. Not until all these sub-tasks are complete can you start on the main task, to construct the shirt.

While completing these sub-tasks, there may be changes, such as the customer wanted a different color, or different buttons, or deciding to cancel the order completely. Due to this ongoing risk of change the subtasks should be completed independent of each other, so that any changes can be made without effecting the entire process, however if there is a cancellation of the order all together, this needs to cancel all sub-tasks, not just one.

So how does this apply to software you are writing in Go?

It is relevant because your program may be doing a range of subtasks concurrently, and although the different tasks should not necessarily all be linked, if there is a cancellation, or a change in the program is made via an incoming request, the entire technical ecosystem needs to know about it.

The problem we are solving here is that Go servers handle incoming requests (kind of individual sub- tasks) as their own go-routines, with each go-routine having individual access to the backend elements, such as a database, of RPC service.

The individual go-routines and requests typically need access to specific values, such as end user identifying data, authorization token, or the request’s deadline, when a request is cancelled, or times out, all the go-routines working on that request should exit quickly so the system can reclaim any resources they were using.

So, the core things to keep in mind with request-scoped values, cancellation signals, and deadlines across API boundaries to all go-routines, that they are handled with clean design. Which is described as cancellation and propagation.

Context Packages

The Context package defines the Context type(interface), which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.

APIs

Creation

Cancellation and Propagation

Request-scoped value and Propagation

Realizing the Uses

Based on our current understanding, after going through all the above links and information I have given you, I will now give you some sample code.

Here is an example of using the time package to enable us to print the message “Hello Go” after 5 seconds. We will call the time.After API from time package:

Now let’s try to print the “Hello Go” message using the context package. Context was created from context.Background or the context.TODO API.

Here you can see a few difference options outlined:

Now let’s think about how context can be passed across the network using the http package, between server and client.

The server will listen on port 8080 for client request, and send our “Hello Go” message to the client. Once the handler receives the request, it gets context from the request, and check if the context is valid. The client will then send the request with context to receive the message from the service, and it will be printed to standard out.

Finally, let’s look at cancellation and propagation between server and client. The server will listen on port 8080 for a client request, and when context got timed out on the client side. The server is then stopped, and returned. The client will send the request with context with timeout, once the timeout context deadline is exceeded and has exited.

Rules of Use

Thank you!

I hope this blog helps beginners of Gophers to understand, and gain confidence using the Go context package, enabling you to dive in and explore more.

References

1. Images from https://www.freepik.com/

2. https://golang.org/pkg/context/

3. https://blog.golang.org/context

4. https://blog.golang.org/pipelines

5. https://dave.cheney.net/2017/08/20/context-isnt-for-cancellation

6. https://www.ardanlabs.com/blog/2019/09/context-package-semantics-in-go.html

7. https://www.youtube.com/watch?v=LSzR0VEraWw

8. https://changelog.com/gotime/143

--

--