douwen0647 2019-07-23 02:07
浏览 246
已采纳

审核有关忽略上下文取消功能的警告

I am passing a timeout context to Server.Shutdown (http package). I don't see that I would ever need to call the cancel function returned so I ignore it. But when I run go vet it says 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?

    go signalShutdown(server, stopCh)

    if err := server.ListenAndServeTLS(cert, key); err != http.ErrServerClosed {
        log.Fatalf("ListenAndServeTLS() error: %v
", 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)
}
  • 写回答

1条回答 默认 最新

  • dqm74406 2019-07-23 07:23
    关注

    ... 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?

    By calling, not discarding the cancel function, as documented:

    context, cancel := context.WithTimeout(context.Background(), ForceShutdownAfter*time.Second)
    defer cancel()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)