登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-10 16:24:36 282浏览 收藏

你在学习Golang相关的知识吗?本文《Go vet 关于忽略上下文取消功能的警告》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我正在将超时上下文传递给 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)
}

解决方案


...context.withtimeout 返回的取消函数应该被调用,而不是丢弃,以避免上下文泄漏

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

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

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

到这里,我们也就讲完了《Go vet 关于忽略上下文取消功能的警告》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>