实现思路
- 在HTTP处理器函数中获取
context.Context
对象,该对象可以从http.Request
中获取。
- 使用
context.Context
的Done
通道来监听取消信号。
- 在处理请求的过程中,定期检查
Done
通道是否接收到取消信号。
- 当接收到取消信号时,停止正在进行的操作,释放相关资源,并返回合适的HTTP状态码。
关键代码片段
package main
import (
"context"
"fmt"
"net/http"
"time"
)
func handler(w http.ResponseWriter, r *http.Request) {
// 获取请求的上下文
ctx := r.Context()
// 模拟一个需要长时间处理的任务
work := func(ctx context.Context) error {
select {
case <-time.After(5 * time.Second):
return nil
case <-ctx.Done():
// 检查是否收到取消信号
return ctx.Err()
}
}
if err := work(ctx); err != nil {
if err == context.Canceled {
// 返回合适的HTTP状态码,这里使用499表示客户端已取消
w.WriteHeader(http.StatusClientClosedRequest)
fmt.Fprintf(w, "Request canceled by client")
} else {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Internal error: %v", err)
}
return
}
// 正常处理完成
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Request processed successfully")
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("Server is listening on :8080")
http.ListenAndServe(":8080", nil)
}