xcontext

package
v0.0.0-...-8299741 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 7, 2024 License: GPL-3.0 Imports: 4 Imported by: 3

Documentation

Overview

Package xcontext provides addons to std package context.

Merging contexts

Merge could be handy in situations where spawned job needs to be canceled whenever any of 2 contexts becomes done. This frequently arises with service methods that accept context as argument, and the service itself, on another control line, could be instructed to become non-operational. For example:

func (srv *Service) DoSomething(ctx context.Context) (err error) {
	defer xerr.Contextf(&err, "%s: do something", srv)

	// srv.serveCtx is context that becomes canceled when srv is
	// instructed to stop providing service.
	origCtx := ctx
	ctx, cancel := xcontext.Merge(ctx, srv.serveCtx)
	defer cancel()

	err = srv.doJob(ctx)
	if err != nil {
		if ctx.Err() != nil && origCtx.Err() == nil {
			// error due to service shutdown
			err = ErrServiceDown
		}
		return err
	}

	...
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Merge

func Merge(parent1, parent2 context.Context) (context.Context, context.CancelFunc)

Merge merges 2 contexts into 1.

The result context:

  • is done when parent1 or parent2 is done, or cancel called, whichever happens first,
  • has deadline = min(parent1.Deadline, parent2.Deadline),
  • has associated values merged from parent1 and parent2, with parent1 taking precedence.

Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.

func MergeChan

func MergeChan(parent1 context.Context, done2 <-chan struct{}) (context.Context, context.CancelFunc)

MergeChan merges context and channel into 1 context.

MergeChan, similarly to Merge, provides resulting context which:

  • is done when parent1 is done or done2 is closed, or cancel called, whichever happens first,
  • has the same deadline as parent1,
  • has the same associated values as parent1.

Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL