首页 > 文章列表 > Golang 函数:用 WithValue 传递上下文数据

Golang 函数:用 WithValue 传递上下文数据

函数 上下文数据
220 2024-10-30

在 Go 中,使用 WithValue 函数可以向 context.Context 添加键值对,实现上下文数据在函数调用链中的传递。具体步骤如下:创建一个根 context。使用 WithValue 添加键值对到 context。在需要时通过 Value 方法从上下文中获取数据。

Golang 函数:用 WithValue 传递上下文数据

Golang 函数:用 WithValue 传递上下文数据

在 Go 中,[context.Context](https://pkg.go.dev/context#Context) 类型用于在函数调用链中传递上下文信息。[context.WithValue](https://pkg.go.dev/context#WithValue) 函数允许我们向上下文中添加自定义键值对,从而可以在需要时使用这些数据。

语法

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

其中:

  • ctx 是要添加数据的上下文。
  • key 是数据的键,可以是任何类型的值(通常是字符串)。
  • val 是要存储在上下文中的数据值。

实战案例

让我们通过一个示例来了解如何在函数中使用 WithValue 传递上下文数据:

package main

import (
    "context"
    "fmt"
    "log"
)

// 用戶資料的型態
type User struct {
    ID int
    Name string
}

func main() {
    // 創建一個根 context
    ctx := context.Background()

    // 使用 WithValue 為用戶資料添加上下文資料
    // key 為 "user_id",val 為 1
    ctx = context.WithValue(ctx, "user_id", 1)

    // 調用函式 getUserInfo,並在其中訪問上下文資料
    userInfo, err := getUserInfo(ctx)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("用戶資訊:ID: %d, 名稱: %sn", userInfo.ID, userInfo.Name)
}

// getUserInfo 函數,它從上下文資料中提取用戶 ID 並使用它查詢資料庫來獲取用戶資訊
func getUserInfo(ctx context.Context) (*User, error) {
    // 從上下文中獲取用戶 ID
    userID, ok := ctx.Value("user_id").(int)
    if !ok {
        return nil, fmt.Errorf("上下文資料中沒有使用者 ID")
    }

    // 查詢資料庫以獲取用戶資訊
    // 此處省略查詢資料庫的代碼

    return &User{
        ID: userID,
        Name: "John Doe",
    }, nil
}

在這個範例中,我們使用 WithValue 在根 context 中添加了一個键值对,其中键是 "user_id",值是 1。當我們調用 getUserInfo 時,它從上下文中提取用戶 ID,並使用它查詢資料庫獲取用戶資訊。

注意:

  • 上下文中的数据是不可変的,这意味着你添加的数据不能被修改。
  • 传递给 WithValue 的键应该足够独特,以避免与其他上下文中使用的键冲突。
  • 过度使用 WithValue 可能会在上下文中产生大量的数据。因此,建议仅在绝对必要时使用它。