在前面的示例中,我们探讨了如何设置一个简单的HTTP服务器。HTTP服务器非常适合用来展示如何使用context.Context来控制取消操作。Context可以携带截止时间、取消信号以及其他请求范围的值,这些信息可以跨API边界和goroutine传递。
package main
import (
"fmt"
"net/http"
"time"
)
func hello(w http.ResponseWriter, req *http.Request) {
// 每一个请求都由net/http机制创建一个context.Context,它可以通过Context()方法获取。
ctx := req.Context()
fmt.Println("server: hello handler started")
defer fmt.Println("server: hello handler ended")
// 在向客户端发送回复之前,等待几秒钟。这可以模拟服务器正在执行的一些工作。在工作过程中,密切关注context的Done()通道,以便接收到应取消工作并尽快返回的信号。
select {
case <-time.After(10 * time.Second):
fmt.Fprintf(w, "hello\\n")
case <-ctx.Done():
// context的Err()方法会返回一个错误,该错误解释了Done()通道被关闭的原因。
err := ctx.Err()
fmt.Println("server:", err)
internalError := http.StatusInternalServerError
http.Error(w, err.Error(), internalError)
}
}
func main() {
// 如同之前一样,我们在“/hello”路由上注册我们的处理器,并开始提供服务。
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8090", nil)
}
运行结果:
go run context.go &
server: hello handler started
server: hello handler ended
server: hello handler started
server: context canceled
server: hello handler ended
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。