go-rest-api icon indicating copy to clipboard operation
go-rest-api copied to clipboard

routing.GracefulShutdown 无效

Open skyfall opened this issue 4 years ago • 1 comments

Describe the bug 关于routing.GracefulShutdown 无效

To Reproduce Steps to reproduce the behavior: 1.设置routing.GracefulShutdown 返回timeout = 5s 2.设置接口 /healthcheck 延迟 3s 3.make build 构建项目 并运行

Expected behavior 请求/healthcheck 接口 马上通过control+c 关闭程序 浏览器显示无法访问

Environment (please complete the following information):

  • OS: MAC(11.0.1)
  • GO: version go1.15.5 darwin/amd64
  • ozzo-routing: v2.3.0

Additional context 替换 代码 后可以正常 `

// go routing.GracefulShutdown(hs, 5*time.Second, logger.Infof)

// make sure idle connections returned
processed := make(chan struct{})
go func() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	<-c

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := hs.Shutdown(ctx); nil != err {
		logger.Errorf("server shutdown failed, err: %v\n", err)
	}
	logger.Infof("server gracefully shutdown")

	close(processed)
}()

logger.Infof("server %v is running at %v", Version, address)
if err := hs.ListenAndServe(); err != nil && err != http.ErrServerClosed {
	logger.Error(err)
	os.Exit(-1)
}

<-processed

`

skyfall avatar Nov 19 '20 06:11 skyfall

修改 可以调整routing.GracefulShutdown 来解决

code

main.go
func main() {
        ....

	// build HTTP server
	address := fmt.Sprintf(":%v", cfg.ServerPort)
	hs := &http.Server{
		Addr:    address,
		Handler: buildHandler(logger, dbcontext.New(db), cfg),
	}
	logger.Infof("server %v is running at %v", Version, address)
	go func() {
		if err := hs.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Error(err)
			os.Exit(-1)
		}
	}()

	// start the HTTP server with graceful shutdown
	routing.GracefulShutdown(hs, 5*time.Second, logger.Infof)

}

skyfall avatar Nov 20 '20 10:11 skyfall