Go - Context

Beginner 10/10 Teacher 10/10 Architect 10/10
Tip: The Sample REST API shows how to pass request-scoped context through handlers.

Basics

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
select{
case <-time.After(2*time.Second):
  fmt.Println("late")
case <-ctx.Done():
  fmt.Println("cancelled:", ctx.Err())
}

In HTTP

*http.Request carries a context; pass it to DB calls and downstream ops.