We're planting a tree for every job application! Click here to learn more

Go Context Explained

Sundara Senthil

21 Dec 2020

3 min read

Go Context Explained
  • Go

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 affecting 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 the 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.

http-goroutines.png

The individual goroutines 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 goroutines 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 goroutines, 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.

type-context.png

APIs

Creation

context-api.png

Cancellation and Propagation

Cancel&propogation.png

Request-scoped value and Propagation

Req-scope Value&propogation.png

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:

timer-hello.png

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

Here you can see a few difference options outlined:

ctxt-Hello.png ctxt-Hello-Output.png

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 ctx 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.

server-http-ctxt.png

client-http-ctxt.png

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.

server-http-ctxt-cancel&propogation.png

client-http-ctxt-cancel&propogation.png

Rules of Use

rules.png

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

Did you like this article?

Sundara Senthil

See other articles by Sundara

Related jobs

See all

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Title

The company

  • Remote

Related articles

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

12 Sep 2021

JavaScript Functional Style Made Simple

JavaScript Functional Style Made Simple

Daniel Boros

12 Sep 2021

WorksHub

CareersCompaniesSitemapFunctional WorksBlockchain WorksJavaScript WorksAI WorksGolang WorksJava WorksPython WorksRemote Works
hello@works-hub.com

Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ

108 E 16th Street, New York, NY 10003

Subscribe to our newsletter

Join over 111,000 others and get access to exclusive content, job opportunities and more!

© 2024 WorksHub

Privacy PolicyDeveloped by WorksHub