We use cookies and other tracking technologies to improve your browsing experience on our site, analyze site traffic, and understand where our audience is coming from. To find out more, please read our privacy policy.

By choosing 'I Accept', you consent to our use of cookies and other tracking technologies.

We use cookies and other tracking technologies to improve your browsing experience on our site, analyze site traffic, and understand where our audience is coming from. To find out more, please read our privacy policy.

By choosing 'I Accept', you consent to our use of cookies and other tracking technologies. Less

We use cookies and other tracking technologies... More

Login or register
to publish this job!

Login or register
to save this job!

Login or register
to save interesting jobs!

Login or register
to get access to all your job applications!

Login or register to start contributing with an article!

Login or register
to see more jobs from this company!

Login or register
to boost this post!

Show some love to the author of this blog by giving their post some rocket fuel 🚀.

Login or register to search for your ideal job!

Login or register to start working on this issue!

Login or register
to save articles!

Login to see the application

Engineers who find a new job through Golang Works average a 15% increase in salary 🚀

You will be redirected back to this page right after signin

Blog hero image

Go Context Explained

Sundara Senthil 21 December, 2020 | 3 min read

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

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

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

Originally published on senthil-sundara.medium.com

Related Issues

open-editions / corpus-joyce-ulysses-tei
open-editions / corpus-joyce-ulysses-tei
  • Started
  • 0
  • 1
  • Intermediate
  • HTML
open-editions / corpus-joyce-ulysses-tei
open-editions / corpus-joyce-ulysses-tei
  • Started
  • 0
  • 2
  • Intermediate
  • HTML
open-editions / corpus-joyce-ulysses-tei
open-editions / corpus-joyce-ulysses-tei
  • Open
  • 0
  • 0
  • Intermediate
  • HTML
open-editions / corpus-joyce-ulysses-tei
open-editions / corpus-joyce-ulysses-tei
  • Open
  • 0
  • 0
  • Intermediate
  • HTML

Get hired!

Sign up now and apply for roles at companies that interest you.

Engineers who find a new job through Golang Works average a 15% increase in salary.

Start with GitHubStart with Stack OverflowStart with Email