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:
Deadline
Return bind currentcontext
The deadline at which tasks are cancelled; Returns if no deadline is setok == false
.Done
When binding the currentcontext
A closed task is returned when the task is canceledchannel
; If the currentcontext
Will not be cancelled and will returnnil
.Err
ifDone
The returnedchannel
Not closed, will returnnil
; ifDone
The returnedchannel
Closed. A non-empty value is returned indicating the reason the task ended. If it iscontext
Been canceled,Err
Will returnCanceled
; If it iscontext
Timeout,Err
Will returnDeadlineExceeded
.Value
returncontext
Store key value pairs in the currentkey
Corresponding 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.