Go Intermediate

Context in Go Programming — Part 1

Basic Usage of Context — WithValue

source: dev.to

Before Go 1.7 came out, context is an external library golang.org/x/net/context and after Go 1.7 was released, context library was added as a built-in library which allows other standard libraries to use context for cancellation, data passing, timeout, especially net/http . In this part, I will discuss context usage in passing request-scoped data.

Release Note: Go 1.7 Release Note


  • Basic of Go Programming
  • Go version ≥ 1.7

The only things you need is basic of Go Programming, channel and goroutine are optional, and go version ≥ 1.7 of Go because we will use context as a built-in library.

Repository: https://github.com/david-yappeter/go-context-examples

Hands On

As we can see inside context library, there are several functions:

  • context.Context{} , is the type of context that we will use.
  • context.Background() , normally it is used to declare a non-nil empty context and the initialize as top-level context (first context) from a request.
  • context.TODO() , it has the same value as context.Background() , but with a different description from the official documentation. We only use this context when we are unsure the context will be used or not yet available.
  • context.WithValue() , takes 3 parameters: parent context, key, and a value. It will return a context.Context{} with the parent value and the value that we have set in the parameter.

Other things like context.WithCancel() , context.WithTimeout() , context.WithDeadline() will be discussed in the next part, stay tuned :).

Let’s start with a simple example:

I will break it down into several parts:

  • First, we create an empty context and assign it into ctx variable.
  • Create 3 contexts with ctx as the parent value, with its key and value.
  • Then we create another context with ctx1 as the parent and give it a key and value.
  • We will try to extract the value from ctx1 , ctx2 , ctx3 with the right key. It will return us the value according to the key.
  • If we try to extract a value from a context with a wrong key, it will return nil value.

Now we will apply this thing into a Rest API with net/http library.



For example, we will create a middleware that gets the data from the token and assign the value to request context (middleware1) and we will use CtxClaim to extract the value later on. We will create a simple HTTP listener on / endpoint.

http.Handle("/", … , and assign the middleware and http.HandlerFunc() inside the middleware that will handle the request. We will set it to listen to port 8080.

Now we only need to run the code with go run main.go , and try to access http://localhost:8080. The output of the program is:

Insert Claim into Context

That’s all about this first part of Context in Go Programming, hope you have a great day :).

Just a normal Go Programmer 👨‍💻