Skip to content

Latest commit

 

History

History
44 lines (32 loc) · 2.68 KB

README.md

File metadata and controls

44 lines (32 loc) · 2.68 KB

Context - Standard Library

The package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.

Notes

  • Incoming requests to a server should create a Context.
  • Outgoing calls to servers should accept a Context.
  • The chain of function calls between them must propagate the Context.
  • Replace a Context using WithCancel, WithDeadline, WithTimeout, or WithValue.
  • When a Context is canceled, all Contexts derived from it are also canceled.
  • Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it.
  • Do not pass a nil Context, even if a function permits it. Pass context.TODO if you are unsure about which Context to use.
  • Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.
  • The same Context may be passed to functions running in different goroutines; Contexts are safe for simultaneous use by multiple goroutines.

Links

Package context
Go Concurrency Patterns: Context - Sameer Ajmani
Cancellation, Context, and Plumbing - Sameer Ajmani
Using contexts to avoid leaking goroutines - JBD

Code Review

"Context values are for request-scoped data that passes through programs in a distributed system. Litmus test: Could it be an HTTP header?" - Sameer Ajmani

Store / Retrieve context values (Go Playground)
WithCancel (Go Playground)
WithDeadline (Go Playground)
WithTimeout (Go Playground)
Request/Response (Go Playground
Cancellation (Go Playground

Exercises

Exercise 1

Use the template and follow the directions. You will be writing a web handler that performs a mock database call but will timeout based on a context if the call takes too long. You will also save state into the context.

Template (Go Playground) | Answer (Go Playground)


All material is licensed under the Apache License Version 2.0, January 2004.