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

AJR*_*AJR -3 go

我将超时上下文传递给 Server.Shutdown (http 包)。我不认为我需要调用返回的取消函数,所以我忽略它。但当我跑去看兽医时,它说the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak

如果没有问题,如何解决问题或避免出现 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)
}
Run Code Online (Sandbox Code Playgroud)

Fli*_*mzy 8

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

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

通过调用,而不是丢弃该cancel函数,如文档所示

context, cancel := context.WithTimeout(context.Background(), ForceShutdownAfter*time.Second)
defer cancel()
Run Code Online (Sandbox Code Playgroud)