context

context #

context是Go1.7版本加入的标准库

context提供的方法 #

创建顶级上下文,返回context.Context接口类型
func Background() Context
func TODO() Context

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
  示例:ctx, cancel := context.WithCancel(context.Background())
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) 
func WithValue(parent Context, key, val interface{}) Context

context.Context接口 #

type Context interface {
    Deadline() (deadline time.Time, ok bool)
    Done() <-chan struct{}
    Err() error
    Value(key interface{}) interface{}
}

使用context.Context接口的注意事项 #

推荐以参数的方式显示传递context.Context接口类型
以context.Context接口类型作为参数的函数方法,应该把Context作为第一个参数。
给一个函数方法传递context.Context的时候,不要传递nil,如果不知道传递什么,就使用context.TODO()
context.Context的Value相关方法应该传递请求域的必要数据,不应该用于传递可选参数
context.Context是线程安全的,可以放心的在多个goroutine中传递

示例1 #



Build by Loppo 0.6.15