Go Context 101

Grasp basics about Go context and avoid pitfalls

Stefanie Lai
CodeX

--

by author

Go context is considered one of the most widely used Go types after its introduction in 1.7. Often combined with goroutines, it simplifies data processing, cancellation, and other operations. As an interface with only four functions, time(Deadline), signal(Done), exception(error), and data(Value), it is not complicated but super-useful in different scenarios, covering almost every aspect in common usage.

type Context interface {// Deadline returns the time when work done on behalf of this context// should be canceled. Deadline returns ok==false when no deadline is// set.Deadline() (deadline time.Time, ok bool)// Done returns a channel that's closed when work done on behalf of this// context should be canceled.Done() <-chan struct{}// Err returns a non-nil error value after Done is closed.Err() error// Value returns the value associated with this context for key.Value(key interface{}) interface{}}

--

--