为了账号安全,请及时绑定邮箱和手机立即绑定

Context.WithTimeout() 和 os.exit in gorilla/mux

Context.WithTimeout() 和 os.exit in gorilla/mux

Go
小唯快跑啊 2022-08-30 21:29:47
我正在使用Golang gorilla / mux包,其中一个例子如下:func main() {    var wait time.Duration    flag.DurationVar(&wait, "graceful-timeout", time.Second * 15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")    flag.Parse()    r := mux.NewRouter()    // Add your routes as needed    srv := &http.Server{        Addr:         "0.0.0.0:8080",        // Good practice to set timeouts to avoid Slowloris attacks.        WriteTimeout: time.Second * 15,        ReadTimeout:  time.Second * 15,        IdleTimeout:  time.Second * 60,        Handler: r, // Pass our instance of gorilla/mux in.    }    // Run our server in a goroutine so that it doesn't block.    go func() {        if err := srv.ListenAndServe(); err != nil {            log.Println(err)        }    }()    c := make(chan os.Signal, 1)    // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)    // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.    signal.Notify(c, os.Interrupt)    // Block until we receive our signal.    <-c    // Create a deadline to wait for.    ctx, cancel := context.WithTimeout(context.Background(), wait)    defer cancel()    // Doesn't block if no connections, but will otherwise wait    // until the timeout deadline.    srv.Shutdown(ctx)    // Optionally, you could run srv.Shutdown in a goroutine and block on    // <-ctx.Done() if your application should wait for other services    // to finalize based on context cancellation.    log.Println("shutting down")    os.Exit(0)}这似乎很简单,但我的理解是,在调用时,延迟不会运行(根据 https://gobyexample.com/exit)。我注意到有一个返回的 by ,然后被推迟。我的猜测是,如果在截止日期之前完成,这应该取消上面创建的上下文,但我不明白在最后调用时会如何发生这种情况。任何人都可以帮我看到我错过了什么吗?os.Exit()CancelFunc()context.WithTimeout()main()os.Exit()
查看完整描述

1 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

你是对的,从不调用延迟取消函数。作者可能想指出,在实际应用中,你永远不应该忘记取消你的上下文。


查看完整回答
反对 回复 2022-08-30
  • 1 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号