
“停止”功能的唯一方法是从其返回。因此,time.Sleep无法中断。改用select语句:
package mainimport ( "fmt" "net/http" "time")func main() { http.ListenAndServe(":3000", otherHandler(time.RFC1123))}func otherHandler(format string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { select { case <-time.After(4 * time.Second): // time's up case <-r.Context().Done(): // client gave up return } tm := time.Now().Format(format) w.Write([]byte("The time is: " + tm)) fmt.Println("response:", "The time is: "+tm) }}通常,在战略位置检查请求上下文(或从中派生的请求上下文)。如果上下文已取消,则不要继续 *** 作和
return。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)