The context command for Golang programming uses

Posted by blr32 on Thu, 29 Aug 2019 07:57:33 +0200

Package context

import "context"

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

A Context context should be created for incoming requests from the server, and the Context context should be accepted for outgoing calls to the server. Function call chains between them must propagate Context context, which can be replaced by a derived Context context created using WithCancel, WithDeadline, WithTimeout or WithValue. When a Context context is cancelled, all Context contexts derived from it are cancelled.

WithCancel, WithDeadline, and WithTimeout functions accept a Context context (parent) and return the derived Context context (child) and CancelFunc. Calling CancelFunc cancels the child and its children, removes the parent's reference to the child, and stops any associated timers. If CancelFunc is not called, the child and its children are leaked until the parent is cancelled or the timer triggers. The Go-Vet tool checks whether the cancellation function is used for all control flow paths.

Programs using Context context should follow these rules to maintain consistency of interfaces between packages and allow static analysis tools to check context propagation:

Instead of storing the context in the structure type, you explicitly pass the Context context to each function that needs it. And the Context context should be the first parameter, usually called ctx:

func DoSomething(ctx context.Context, arg Arg) error {
	// ... use ctx ...
}

Never pass a nil context, even if the function allows it. If you are not sure which Context context to use, pass context.TODO.

Use Context context values only for request range data of transport processes and API s, not for passing optional parameters to functions.

The same Context context can be passed to functions running in different goroutines; context is safe for multiple goroutines to be used simultaneously.

see also https://blog.golang.org/context To get sample code for a server that uses context.

Index

Variables

type CancelFunc

type Context

func Background

func TODO

func WithCancel

func WithDeadline

func WithTimeout

func WithValue

Variables

var Canceled = errors.New("context canceled") var DeadlineExceeded error = deadlineExceededError{}

type CancelFunc

type CancelFunc func()

type Context

type Context interface {
    // Deadline returns the time when work done on behalf of this context
    // should be canceled. Deadline returns ok==false when no deadline is
    // set. Successive calls to Deadline return the same results.
    Deadline() (deadline time.Time, ok bool)

    // Done returns a channel that's closed when work done on behalf of this
    // context should be canceled. Done may return nil if this context can
    // never be canceled. Successive calls to Done return the same value.
    //
    // WithCancel arranges for Done to be closed when cancel is called;
    // WithDeadline arranges for Done to be closed when the deadline
    // expires; WithTimeout arranges for Done to be closed when the timeout
    // elapses.
    //
    // Done is provided for use in select statements:
    //
    //  // Stream generates values with DoSomething and sends them to out
    //  // until DoSomething returns an error or ctx.Done is closed.
    //  func Stream(ctx context.Context, out chan<- Value) error {
    //  	for {
    //  		v, err := DoSomething(ctx)
    //  		if err != nil {
    //  			return err
    //  		}
    //  		select {
    //  		case <-ctx.Done():
    //  			return ctx.Err()
    //  		case out <- v:
    //  		}
    //  	}
    //  }
    //
    // See https://blog.golang.org/pipelines for more examples of how to use
    // a Done channel for cancelation.
    Done() <-chan struct{}

    // Err returns a non-nil error value after Done is closed. Err returns
    // Canceled if the context was canceled or DeadlineExceeded if the
    // context's deadline passed. No other values for Err are defined.
    // After Done is closed, successive calls to Err return the same value.
    Err() error

    // Value returns the value associated with this context for key, or nil
    // if no value is associated with key. Successive calls to Value with
    // the same key returns the same result.
    //
    // Use context values only for request-scoped data that transits
    // processes and API boundaries, not for passing optional parameters to
    // functions.
    //
    // A key identifies a specific value in a Context. Functions that wish
    // to store values in Context typically allocate a key in a global
    // variable then use that key as the argument to context.WithValue and
    // Context.Value. A key can be any type that supports equality;
    // packages should define keys as an unexported type to avoid
    // collisions.
    //
    // Packages that define a Context key should provide type-safe accessors
    // for the values stored using that key:
    //
    // 	// Package user defines a User type that's stored in Contexts.
    // 	package user
    //
    // 	import "context"
    //
    // 	// User is the type of value stored in the Contexts.
    // 	type User struct {...}
    //
    // 	// key is an unexported type for keys defined in this package.
    // 	// This prevents collisions with keys defined in other packages.
    // 	type key int
    //
    // 	// userKey is the key for user.User values in Contexts. It is
    // 	// unexported; clients use user.NewContext and user.FromContext
    // 	// instead of using this key directly.
    // 	var userKey key = 0
    //
    // 	// NewContext returns a new Context that carries value u.
    // 	func NewContext(ctx context.Context, u *User) context.Context {
    // 		return context.WithValue(ctx, userKey, u)
    // 	}
    //
    // 	// FromContext returns the User value stored in ctx, if any.
    // 	func FromContext(ctx context.Context) (*User, bool) {
    // 		u, ok := ctx.Value(userKey).(*User)
    // 		return u, ok
    // 	}
    Value(key interface{}) interface{}
}

func Background

func Background() Context

func TODO

func TODO() Context

func WithCancel

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)

func WithDeadline

func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)

func WithTimeout

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

func WithValue

func WithValue(parent Context, key, val interface{}) Context

Topics: Programming