golang服务器中间件请求取消

golang服务器中间件请求取消,第1张

golang服务器中间件请求取消

“停止”功能的唯一方法是从其返回。因此,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



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5082548.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-16
下一篇2022-11-16

发表评论

登录后才能评论

评论列表(0条)

    保存