go的Context运用记录

当遇到慢速查询时的超时处理

package main

import (
	"context"
	"fmt"
	"net/http"
	"time"
)

func simulateSlowDatabaseQuery(ctx context.Context) (string, error) {
	select {
	case <-ctx.Done(): // 如果上下文被取消了
		return "", ctx.Err() // 返回错误
	case <-time.After(3 * time.Second): // 或者在3秒后完成
		return "查询结果", nil
	}
}

func handler(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
	defer cancel()

	result, err := simulateSlowDatabaseQuery(ctx)
	if err != nil {
		http.Error(w, "请求超时", http.StatusRequestTimeout)
		return
	}

	fmt.Fprintln(w, result)

}

func main() {
	http.HandleFunc("/", handler)
	fmt.Println("Server is running on :8080")
	http.ListenAndServe(":8080", nil)
}

posted @ 2024-04-30 13:38  Jikefan  阅读(6)  评论(0)    收藏  举报