说明
Context上下文用于控制函数调用链,所有进入服务的请求需要创建Context,调用其他服务需要接受一个Context,Context需要在函数调用链中进行传播。
使用WithCancel,WithDeadline,WithTimeout,WithVaule,可以从一个Context上派生出子Context,并得到CancelFunc。调用CancelFunc可以关闭子Context及其派生出来的Context。
使用Context的程序需要遵循如下原则:
1.不要将Context存储在结构当中,而是将其作为函数参数传递给函数
2.Context作为函数的第一个参数,并使用ctx作为参数名称。
3.不要传入nil Context,如果不知道使用哪种Context,可以使用Context.TODO替代
Context是gorouting安全的,可以被不同的gorouting访问
使用
错误码
- var Canceled = errors.New("context canceled")
当Context cancel的时候,通过Context.Err返回该错误 - var DeadlineExceeded error = deadlineExceededError{}
当Context达到Deadline时,通过Context.Err返回该错误。
方法
-
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
返回parent Context的拷贝,该拷贝使用新的Done channel。当cancelFunc被调用或者父Context关闭时,Context的Done channel关闭。 -
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
返回带最后期限的parent Context的拷贝,使用新的Done channel。Context的存活时间不能超过d,如果父Context的Deadline早于d那么子Context的存活时间将设置为与父Context相同。
如果d超时或调用了cancelFunc或父Context关闭则该Context也关闭 -
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)<