Skip to content

Repository files navigation

ctxutil

Build StatuscodecovgolangciGoDocgoreadme

Package ctxutil is a collection of functions for contexts.

Functions

func Interrupt() context.Context

Interrupt is a convenience function for catching SIGINT on a background context.

Example:

funcmain() {
ctx:=ctxutil.Interrupt()
// use ctx...
}

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.

Example

funcmain() {
// Create a context which will be cancelled on SIGINT.ctx:=ctxutil.WithSignal(context.Background(), os.Interrupt)
// use ctx...
}

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:

  1. Middlewares that extract user credentials and request id from the
headersandinjectthemtothe`http.Request`contextasvalues.
  1. The http.Handler launches an asynchronous goroutine task which
needsthosevaluesfromthecontext.
  1. After launching the asynchronous task the handler returns 202 to
theclient, thegoroutinecontinuestoruninbackground.

Problem Statement:

  • The async task can't use the request context - it is cancelled
asthe`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` (extracttherequestidfromthecontextandinjectittohttpheadersinafollowingrequest.)

The suggested function ctx := ctxutil.WithValues(ctx, values) does the following:

  1. When ctx.Value() is called, the key is searched in the
original`ctx`andifnotfounditsearchesin`values`.
  1. When Done()/Deadline()/Err() are called, it is uses
original`ctx`'s state.

Example

This is how an http.Handler should run a goroutine that need values from the context.

funchandle(w http.ResponseWriter, r*http.Request) {
// [ do something ... ]// Create async task context that enables it run for 1 minute, for exampleasyncCtx, asyncCancel=ctxutil.WithTimeout(context.Background(), time.Minute)
// Use values from the request contextasyncCtx=ctxutil.WithValues(asyncCtx, r.Context())
// Run the async task with it's contextgofunc() {
deferasyncCancel()
asyncTask(asyncCtx)
}()
}

Created by goreadme

About

utils for Go context

Topics

Resources

Stars

26 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages