Golang中HTTP的Context使用有哪些资源

Golang中HTTP的Context使用有哪些资源 关于HTTP中Context的任何资源

2 回复

也许你可以详细说明一下问题?我不太明白。

更多关于Golang中HTTP的Context使用有哪些资源的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Golang的HTTP处理中,Context主要用于管理请求生命周期和传递请求范围内的数据。以下是Context使用的主要资源:

1. 请求超时控制

func handler(w http.ResponseWriter, r *http.Request) {
    ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
    defer cancel()
    
    // 在超时控制的上下文中执行操作
    select {
    case <-time.After(3 * time.Second):
        fmt.Fprint(w, "请求成功完成")
    case <-ctx.Done():
        http.Error(w, "请求超时", http.StatusGatewayTimeout)
    }
}

2. 传递请求范围数据

type key string

const userKey key = "user"

func middleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // 在Context中存储用户信息
        ctx := context.WithValue(r.Context(), userKey, "john.doe@example.com")
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

func handler(w http.ResponseWriter, r *http.Request) {
    // 从Context中获取用户信息
    if user, ok := r.Context().Value(userKey).(string); ok {
        fmt.Fprintf(w, "当前用户: %s", user)
    }
}

3. 取消传播

func longRunningTask(ctx context.Context) error {
    for i := 0; i < 10; i++ {
        select {
        case <-ctx.Done():
            return ctx.Err() // 当父Context取消时立即返回
        default:
            time.Sleep(1 * time.Second)
            fmt.Printf("处理中... %d\n", i)
        }
    }
    return nil
}

func handler(w http.ResponseWriter, r *http.Request) {
    go longRunningTask(r.Context())
    fmt.Fprint(w, "任务已启动")
}

4. 数据库查询超时

func dbQueryHandler(w http.ResponseWriter, r *http.Request) {
    ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
    defer cancel()
    
    // 模拟数据库查询
    result := make(chan string, 1)
    go func() {
        time.Sleep(2 * time.Second) // 模拟查询耗时
        result <- "查询结果"
    }()
    
    select {
    case res := <-result:
        fmt.Fprint(w, res)
    case <-ctx.Done():
        http.Error(w, "数据库查询超时", http.StatusRequestTimeout)
    }
}

5. 外部API调用

func callExternalAPI(ctx context.Context, url string) (string, error) {
    req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
    if err != nil {
        return "", err
    }
    
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()
    
    body, err := io.ReadAll(resp.Body)
    return string(body), err
}

6. 请求追踪

const traceIDKey = "trace-id"

func tracingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        traceID := r.Header.Get("X-Trace-ID")
        if traceID == "" {
            traceID = uuid.New().String()
        }
        
        ctx := context.WithValue(r.Context(), traceIDKey, traceID)
        w.Header().Set("X-Trace-ID", traceID)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

这些示例展示了Context在HTTP处理中的核心用途:超时控制、取消传播、数据传递和请求追踪。

回到顶部