golang contextcontext

1. Why context is needed

In the Server of the Go http package, each request has a corresponding goroutine to handle it. Request processing functions usually start additional goroutines to access back-end services, such as databases and RPC services.

The goroutine used to process a request usually needs to access some data specific to the request, such as the end user's identity authentication information, verification-related tokens, and the request's deadline. When a request is canceled or times out, all goroutines used to handle the request should exit quickly before the system can release the resources occupied by these goroutines.

2. context interface

context.ContextIt is an interface that defines four methods that need to be implemented.

grammar:


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

方法解释:

	Deadline():返回当前Context被取消的时间,也就是完成工作的截止时间(deadline);
	
	Done():返回一个Channel,这个Channel会在当前工作完成或者上下文被取消之后关闭,多次调用Done方法会返回同一个Channel;
	
	Err():返回当前Context结束的原因,它只会在Done返回的Channel被关闭时才会返回非空的值;如果当前Context被取消就会返回Canceled错误;如果当前Context超时就会返回DeadlineExceeded错误;
	
	Value():从Context中返回键对应的值,对于同一个上下文来说,多次调用Value 并传入相同的Key会返回相同的结果;


3. Background method

grammar:


context.Background() Context

Analysis: Background() is mainly used in the main function, initialization and test code, as the Context of the Context tree structure 最顶层, which is the root Context.

4. with series functions

1.WithCancel method

WithCancel returns a copy of the parent node with a new Done channel. The returned context's Done channel is closed when the returned cancel function is called or when the parent context's Done channel is closed.

grammar:


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

2, WithDeadline method

Returns a copy of the parent context, deadlineadjusted to no later than d. If the parent context's deadline is already earlier than d, WithDeadline(parent, d) is semantically equivalent to the parent context. The returned context's Done channel will be closed when the deadline expires or when the returned cancel function is called or when the parent context's Done channel is closed, whichever occurs first.

grammar:


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

3.WithTimeout method

WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).

grammar:


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

4.WithValue method

The WithValue function can establish a relationship between the data in the request scope and the Context object. WithValue returns a copy of the parent node where the value associated with key is val.

grammar:


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

5. Precautions for use

  1. It is recommended to pass the Context explicitly in the form of parameters.
  2. Function methods that take Context as a parameter should use Context as the first parameter.
  3. When passing Context to a function method, do not pass nil. If you don’t know what to pass, usecontext.Background()
  4. The Value related methods of Context should pass the necessary data of the request field and should not be used to pass optional parameters.
  5. Context Yes 线程安全, you can safely pass it in multiple goroutines

Guess you like

Origin blog.csdn.net/change_any_time/article/details/128986783