Black Lives Matter. Support the Equal Justice Initiative.

Package context

import "context"
Overview
Index
Examples

Overview ▾

包上下文定义了上下文类型,该类型在API边界之间以及进程之间携带截止日期,取消信号和其他请求范围的值.

对服务器的传入请求应创建一个上下文,而对服务器的传出调用应接受一个上下文. 它们之间的函数调用链必须传播Context,可以选择将其替换为使用WithCancel,WithDeadline,WithTimeout或WithValue创建的派生Context. 取消上下文后,从该上下文派生的所有上下文也会被取消.

WithCancel,WithDeadline和WithTimeout函数采用Context(父级)并返回派生的Context(子级)和CancelFunc. 调用CancelFunc会取消该子代及其子代,删除父代对该子代的引用,并停止所有关联的计时器. 未能调用CancelFunc会使子代及其子代泄漏,直到父代被取消或计时器触发. 审核工具检查所有控制流路径上是否都使用了CancelFuncs.

使用上下文的程序应遵循以下规则,以使各个包之间的接口保持一致,并启用静态分析工具来检查上下文传播:

不要将上下文存储在结构类型中; 而是将上下文明确传递给需要它的每个函数. Context应该是第一个参数,通常命名为ctx:

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

即使函数允许,也不要传递nil Context. 如果不确定使用哪个上下文,请传递context.TODO.

仅将上下文值用于传递过程和API的请求范围的数据,而不用于将可选参数传递给函数.

可以将相同的上下文传递给在不同goroutine中运行的函数. 上下文对于由多个goroutine同时使用是安全的.

有关使用上下文的服务器的示例代码,请参见https://blog.golang.org/context .

Variables

取消是Context.Err取消上下文时返回的错误.

var Canceled = errors.New("context canceled")

DeadlineExceeded是上下文的最后期限过去时Context.Err返回的错误.

var DeadlineExceeded error = deadlineExceededError{}

func WithCancel 1.7

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

WithCancel返回具有新的"完成"通道的父级副本. 当调用返回的cancel函数或关闭父上下文的Done通道时(以先发生者为准),关闭返回的上下文的Done通道.

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

Example

此示例演示了使用可取消上下文来防止goroutine泄漏. 在示例函数结束时,由gen启动的goroutine将返回而不会泄漏.

1
2
3
4
5

func WithDeadline 1.7

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

WithDeadline返回父上下文的副本,并将截止日期调整为不迟于d. 如果父级的截止日期早于d,则WithDeadline(parent,d)在语义上等效于父级. 当截止日期到期,调用返回的cancel函数或关闭父上下文的Done通道(以先到者为准)时,将关闭返回的上下文的Done通道.

取消此上下文将释放与其关联的资源,因此在此上下文中运行的操作完成后,代码应立即调用cancel.

Example

此示例传递一个带有任意截止日期的上下文,以告知阻塞函数它应在到达工作后立即放弃工作.

context deadline exceeded

func WithTimeout 1.7

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

WithTimeout返回WithDeadline(parent,time.Now().Add(timeout)).

取消此上下文将释放与之关联的资源,因此在此上下文中运行的操作完成后,代码应立即调用cancel:

func slowOperationWithTimeout(ctx context.Context) (Result, error) {
	ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
	defer cancel()  // releases resources if slowOperation completes before timeout elapses
	return slowOperation(ctx)
}

Example

此示例传递带有超时的上下文,以告知阻塞函数在超时结束后应放弃工作.

context deadline exceeded

type CancelFunc 1.7

CancelFunc告诉操作放弃其工作. CancelFunc不等待工作停止. 多个goroutine可以同时调用CancelFunc. 在第一个调用之后,随后对CancelFunc的调用什么也不做.

type CancelFunc func()

type Context 1.7

上下文在API边界上带有截止日期,取消信号和其他值.

上下文的方法可以同时由多个goroutine调用.

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.
    // The close of the Done channel may happen asynchronously,
    // after the cancel function returns.
    //
    // 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 cancellation.
    Done() <-chan struct{}

    // If Done is not yet closed, Err returns nil.
    // If Done is closed, Err returns a non-nil error explaining why:
    // Canceled if the context was canceled
    // or DeadlineExceeded if the context's deadline passed.
    // After Err returns a non-nil error, successive calls to Err return the same error.
    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
    //
    // 	// 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 1.7

func Background() Context

Background返回一个非空的Context. 它永远不会被取消,没有价值,也没有期限. 它通常由主要功能,初始化和测试使用,并用作传入请求的顶级上下文.

func TODO 1.7

func TODO() Context

TODO返回一个非空的Context. 当不清楚要使用哪个上下文或尚不可用时(因为尚未扩展周围的功能以接受Context参数),代码应使用context.TODO.

func WithValue 1.7

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

WithValue返回父项的副本,其中与键关联的值为val.

仅将上下文值用于传递过程和API的请求范围的数据,而不用于将可选参数传递给函数.

提供的密钥必须是可比较的,并且不能为字符串类型或任何其他内置类型,以避免使用上下文在程序包之间发生冲突. WithValue的用户应定义自己的键类型. 为了避免在分配给接口{}时进行分配,上下文键通常具有具体的类型struct {}. 或者,导出的上下文键变量的静态类型应为指针或接口.

Example

此示例演示如何将值传递给上下文,以及如何将其检索(如果存在).

found value: Go
key not found: color

by  ICOPY.SITE