gpt4 book ai didi

关于忽略上下文取消功能的 vert 警告

转载 作者:数据小太阳 更新时间:2023-10-29 03:43:36 26 4
gpt4 key购买 nike

我正在将超时上下文传递给 Server.Shutdown(http 包)。我看不出我需要调用返回的取消函数,所以我忽略了它。但是当我运行 go vet 时,它说 context.WithTimeout 返回的取消函数应该被调用,而不是被丢弃,以避免上下文泄漏

如果没有问题,我该如何解决问题或避免 go vet 错误消息?

    go signalShutdown(server, stopCh)

if err := server.ListenAndServeTLS(cert, key); err != http.ErrServerClosed {
log.Fatalf("ListenAndServeTLS() error: %v\n", err)
}
// Note: exit here does not terminate main()
}

// signalShutdown waits for a notification from the OS that the http server
// should be shutdown, then gracefully stops it.
func signalShutdown(server *http.Server, stopCh <-chan struct{}) {
const ForceShutdownAfter = 10 // Shutdown context times out after this many seconds

// Setup chan to receive notification of when server should shut down
quitCh := make(chan os.Signal, 1)
signal.Notify(quitCh, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)

// Wait until we get a notification to stop the server
select {
case <-quitCh:
log.Println("WEB : OS signal received on", server.Addr)
case <-stopCh:
log.Println("WEB : Shutdown message received on", server.Addr)
}

context, _ := context.WithTimeout(context.Background(), ForceShutdownAfter*time.Second)

// Tell the server to shutdown but only after blocking new connections and waiting for the
// existing connections to finish (OR if context expires - see ForceShutdownAfter above)
if err := server.Shutdown(context); err != nil {
log.Fatalf("Shutdown() error: %v", err)
}

os.Exit(0)
}

最佳答案

... the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak.

How do I fix the problem or avoid the go vet error message, if there is no problem?

通过调用而不丢弃cancel 函数,as documented :

context, cancel := context.WithTimeout(context.Background(), ForceShutdownAfter*time.Second)
defer cancel()

关于关于忽略上下文取消功能的 vert 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57155776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com