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) }
本文作者:jikefan
本文链接:https://www.cnblogs.com/jikefan/articles/18167882
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。