golang的context如何使用
时间: 2024-04-30 19:23:00 浏览: 7
Go语言的context包提供了可以在多个Goroutine之间传递请求范围数据的方法,可以用于取消操作、超时处理、请求域传递等场景。
context使用步骤:
1. 创建context
```go
ctx := context.Background()
```
2. 创建带有超时时间的context
```go
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel() // 超时后自动取消context
```
3. 创建带有取消信号的context
```go
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // 手动取消context
```
4. 在Goroutine中传递context
```go
func foo(ctx context.Context) {
select {
case <-ctx.Done():
return
default:
// do something
}
}
```
5. 使用context的value传递数据
```go
ctx := context.WithValue(context.Background(), "key", "value")
value := ctx.Value("key")
```
6. 传递context
```go
func bar(ctx context.Context) {
ctx = context.WithValue(ctx, "key", "value")
foo(ctx)
}
```
7. 获取context的元数据
```go
// 返回context的剩余时间
deadline, ok := ctx.Deadline()
// 返回context是否已经被取消
canceled := ctx.Err()
```