亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 79 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號