Go Context Usage Guide

In Go language, Context is used to pass data within the scope of a request, signal cancellation, and handle the deadline for requests. Context is an interface type defined as follows:

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

The basic steps for using Context are as follows:

  1. Establish Context

You can create an empty Context using the context.Background() function, or you can create a Context with cancellation, deadline, or timeout using the context.WithCancel(), context.WithDeadline(), or context.WithTimeout() functions. For example:

ctx, cancel := context.WithCancel(context.Background())
defer cancel()
  1. Pass the Context as a parameter in functions that require it to be passed.

By putting Context as the first parameter in the function signature, you can then use that Context inside the function. For example:

func doSomething(ctx context.Context) {
    // 使用ctx进行操作
}
  1. Control the lifecycle of a request through Context.

One option is to use the methods provided by Context to retrieve the deadline, cancellation signal, or check if the Context has already ended. For example:

deadline, ok := ctx.Deadline()
done := ctx.Done()
err := ctx.Err()
  1. Passing data through context.

One option: You can use the Value() method of Context to pass data within the Context. The key must be a comparable type, while the value can be any type. For example:

key := "key"
value := "value"
ctx := context.WithValue(context.Background(), key, value)

In general, using Context can help us effectively manage the lifecycle of requests, control concurrency, and pass data. In the standard library of the Go language, many packages offer APIs that support Context.

bannerAds