Package ctxutil is a collection of functions for contexts.
func Interrupt
func Interrupt() context.Context
Interrupt is a convenience function for catching SIGINT on a background context.
func main() {
ctx := ctxutil.Interrupt()
// use ctx...
}
func WithSignal
func WithSignal(parent context.Context, sigWhiteList ...os.Signal) context.Context
WithSignal returns a context which is done when an OS signal is sent. parent is a parent context to wrap. sigWhiteList is a list of signals to listen on. According to the signal.Notify behavior, an empty list will listen to any OS signal. If an OS signal closed this context, ErrSignal will be returned in the Err() method of the returned context.
This method creates the signal channel and invokes a goroutine.
func main() {
// Create a context which will be cancelled on SIGINT.
ctx := ctxutil.WithSignal(context.Background(), os.Interrupt)
// use ctx...
}
func WithValues
func WithValues(ctx, values context.Context) context.Context
WithValues composes values from multiple contexts.
It returns a context that exposes the deadline and cancel of ctx
,
and combined values from ctx
and values
.
A value in ctx
context overrides a value with the same key in values
context.
Consider the following standard HTTP Go server stack:
- Middlewares that extract user credentials and request id from the
headers and inject them to the `http.Request` context as values.
- The
http.Handler
launches an asynchronous goroutine task which
needs those values from the context.
- After launching the asynchronous task the handler returns 202 to
the client, the goroutine continues to run in background.
Problem Statement:
- The async task can't use the request context - it is cancelled
as the `http.Handler` returns.
- There is no way to use the context values in the async task.
- Specially if those values are used automatically with client
`http.Roundtripper` (extract the request id from the context
and inject it to http headers in a following request.)
The suggested function ctx := ctxutil.WithValues(ctx, values)
does the following:
- When
ctx.Value()
is called, the key is searched in the
original `ctx` and if not found it searches in `values`.
- When
Done()
/Deadline()
/Err()
are called, it is uses
original `ctx`'s state.
This is how an http.Handler
should run a goroutine that need
values from the context.
func handle(w http.ResponseWriter, r *http.Request) {
// [ do something ... ]
// Create async task context that enables it run for 1 minute, for example
asyncCtx, asyncCancel = ctxutil.WithTimeout(context.Background(), time.Minute)
// Use values from the request context
asyncCtx = ctxutil.WithValues(asyncCtx, r.Context())
// Run the async task with it's context
go func() {
defer asyncCancel()
asyncTask(asyncCtx)
}()
}
Created by goreadme