The main use of context is, in a word, to control the lifecycle of a Goroutine. This Context is used when we want to abort a goroutine task after it has been taken on by a goroutine for some reason (timeout, or forced exit).

Calls to the Context should be chained, derivingthe new Context with WithCancel, WithDeadline, WithTimeout, or WithValue. When the parent Context is cancelled, all derived contexts are cancelled.

type Context interface {

    Deadline() (deadline time.Time, ok bool)

    Done() <-chan struct{}

    Err() error

    Value(key interface{}) interface{}
}
Copy the code

The Context interface contains four methods:

  • DeadlineReturn bind currentcontextThe deadline at which tasks are cancelled; Returns if no deadline is setok == false.
  • DoneWhen binding the currentcontextA closed task is returned when the task is canceledchannel; If the currentcontextWill not be cancelled and will returnnil.
  • ErrifDoneThe returnedchannelNot closed, will returnnil; ifDoneThe returnedchannelClosed. A non-empty value is returned indicating the reason the task ended. If it iscontextBeen canceled,ErrWill returnCanceled; If it iscontextTimeout,ErrWill returnDeadlineExceeded.
  • ValuereturncontextStore key value pairs in the currentkeyCorresponding value, if there is no corresponding valuekey, the returnnil.

As you can see, the channel returned by the Done method is used to transmit the end signal to preempt and interrupt the current task; The Deadline method indicates whether the current goroutine will be cancelled after some time; And an Err method to explain why goroutine was canceled; Value is used to get additional information specific to the current task tree. And the additional information that context contains how are key-value pairs stored? In fact, you can imagine a tree. Each node of the tree may carry a set of key-value pairs. If the value of the key cannot be found on the current node, it will look up the parent node to the root node.