Go Package context
External
Internal
Overview
Concepts
Context
context.Context
is an interface exposed by the context
package, aimed at being implemented by the Context instances. The Context
instances will flow through your system in the same way done
channels do. Each function downstream from the top level concurrent call would take Context
as its first argument.
The implementations ensure that they are concurrent-safe, so their methods may be called by multiple goroutines simultaneously.
Parent/Child Relationship
Deadline
Timeout
TODO
Manage goroutines lifecycles.
If you have a component that blocks for any reason (disk, network IO, user), then it should probably take the context as a first parameter.
type reportStore interface {
listTimes(ctx context.Context, ...) (..., error)
writeFile(ctx context.Context, ...) error
serveFile(ctx context.Context, ...) error
}
Using the value propagation feature of the Context is dubious. Don't use Context.value for stuff that should be regular dependencies between components. Use Context.value for data that can be passed to your program in any other way: only data that is request-scoped, stuff that is created at the beginning of a request lifecycle, like request ID, etc. If the information is available when the program starts or at any point prior to when the request starts, do not use context.value. This is the case for database handles, loggers, etc.
- https://go.dev/blog/context
- All functions performing I/O operations must accept context. Why? https://learning.oreilly.com/library/view/microservices-with-go/9781804617007/B18865_02.xhtml#:-:text=all%20functions%20performing
- What is with the _ context.Context https://learning.oreilly.com/library/view/microservices-with-go/9781804617007/B18865_02.xhtml#:-:text=(_%20context.Context