qiangxue / go-rest-api

An idiomatic Go REST API starter kit (boilerplate) following the SOLID principles and Clean Architecture
MIT License
1.46k stars 270 forks source link

routing.GracefulShutdown 无效 #14

Open skyfall opened 3 years ago

skyfall commented 3 years ago

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):

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 commented 3 years ago

修改 可以调整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)

}