Home  >  Article  >  What is ctx in golang

What is ctx in golang

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2023-06-09 14:34:082728browse

ctx in Golang is the abbreviation of Context, which is a type in the standard library and is used to transfer metadata such as request scope-specific values, cancellation signals, and deadlines between "goroutines".

What is ctx in golang

Operating system for this tutorial: Windows 10 system, Go1.20.1 version, Dell G3 computer.

In Golang, ctx is the abbreviation of Context, which is a type in the standard library.

TheContext type is used to pass metadata such as request scope-specific values, cancellation signals, and deadlines between goroutines. When creating a request, a root Context can be created and passed into the call chain throughout the application. As requests propagate, this Context can be copied by other goroutines and used for underlying communication.

ctx The main functions are:

  • Transfer metadata: Some metadata information (such as user authorization Token) needs to be passed and used along the way in the HTTP request network call chain , ctx is the preferred method to implement this scenario.

  • Control flow timeout and cancellation: In multi-level function nested call chains, errors often need to penetrate each layer of call chains. In some cases, Goroutine and ctx even need to be canceled at the same time. This is the essential way to solve this kind of problem.

The following is a simple sample code that illustrates how to use ctx to control the cancellation and timeout of goroutine.

func main() {
   ctx, cancel := context.WithCancel(context.Background())
   defer cancel() // 常用结合 defer 安排执行
   go doSomething(ctx)
   time.Sleep(10 * time.Second)
}
func doSomething(ctx context.Context) {
   select {
      case <-time.After(time.Hour):
         fmt.Println("do something")
      case <-ctx.Done():
         fmt.Println("canceled by user:", ctx.Err())
      }
}

In the sample code, use `context.WithCancel` to create a Context, and then pass the cancellation function (`cancel()`) to the `doSomething` function. In `doSomething`, 2 of the channels are monitored through `select`. When 10 seconds pass, the main goroutine executes the `cancel` function, thereby sending a Done signal to `ctx`, which causes the goroutine of `doSomething` Receive this signal and

The above is the detailed content of What is ctx in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn