【问题标题】:Context.WithTimeout() and os.exit in gorilla/muxgorilla/mux 中的 Context.WithTimeout() 和 os.exit
【发布时间】:2021-08-05 06:13:30
【问题描述】:

我使用的是 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)
}

这看起来很简单,但我的理解是当调用os.Exit() 时不会运行延迟(根据https://gobyexample.com/exit)。我注意到context.WithTimeout() 返回了一个CancelFunc(),然后将其延迟。我的猜测是,如果main() 在截止日期之前完成,这应该会取消上面创建的上下文,但我不知道在最后调用os.Exit() 会发生这种情况。谁能帮我看看我错过了什么?

【问题讨论】:

    标签: go server gorilla mux


    【解决方案1】:

    没错,延迟取消函数永远不会被调用。作者可能想指出,在实际应用中,你永远不要忘记取消你的上下文。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-22
      • 2017-06-19
      • 2014-12-21
      • 1970-01-01
      • 2014-11-30
      • 2015-05-11
      • 2018-01-04
      • 2015-04-07
      相关资源
      最近更新 更多