Golang context ELI5

Giuseppe Crinò
1 min readJun 9, 2022

It takes few seconds to find out contexts in Go are shared state across functions and goroutines. But what are examples of things people store in this shared state?

gocql is a library for communicating with Cassandra instances. Before executing a query you can call Query.WithContext(ctx)

WithContext returns a shallow copy of q with its context set to ctx. The provided context controls the entire lifetime of executing a query, queries will be canceled and return once the context is canceled.

Say we want queries to last no more than 10 seconds. We can create a context that's canceled after 10 second

ctx := context.Background()
ctx, err := context.WithTimeout(ctx, 10*time.Millisecond)
session.Query("select c from t").WithContext(ctx)...

Or we receive an HTTP request and we don't want to process that if the TCP connection is closed by the client: use http.Request.Context

http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
if ctx.Err() != nil {
// context cancelled: stop processing here
}
// else: happy path here})

Using context is incredibly useful in making a better use of resources:

  • in the server for cancelling requests from clients that disconnect
  • in the client for finishing serving requests before the server shuts down (because of rollout for example)

--

--