package main
import (
"log"
"net/http"
"os"
"time"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
select {
case <-ctx.Done():
log.Printf("context cancelled")
case <-time.After(time.Minute):
w.Write([]byte("OK"))
log.Printf("request completed. path=%s", r.URL.Path)
}
})
log.Fatal(http.ListenAndServe(":"+port, nil))
}
在本地运行此代码,在发送到http://localhost:8080的curl请求被ctrl-c取消后,日志中将显示“上下文已取消”。将服务部署在云端并取消相同的请求,将在1分钟后在日志中显示为成功请求。