dongwupu5991 2017-11-30 09:53
浏览 539
已采纳

如何在Gin框架中添加after回调

I need to quit the application with os.Exit(0) AFTER HTTP request has finished completely. My application asks another server if it needs an upgrade, so I need to quit for performing a self upgrade with a reboot, but I don't want to break current HTTP request.

When I try to quit in middleware after c.Next() or at the end of handler function, the browser gives error: localhost didn’t send any data.

How this can be done?

  • 写回答

2条回答 默认 最新

  • dongqiang2024 2017-12-03 16:34
    关注

    As you say, your program is terminating before the HTTP connection completes cleanly - you need to wait for the HTTP transaction to finish and then exit. Fortunately since Go 1.8 http.Server has a Shutdown method that does what you need.

    Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down.

    So, the general approach would be:

    exitChan := make(chan struct{})
    
    // Get a reference to exitChan to your handlers somehow
    
    h := &http.Server{
        // your config
    }
    go func(){
        h.ListenAndServe() // Run server in goroutine so as not to block
    }()
    
    <-exitChan // Block on channel
    h.Shutdown(nil) // Shutdown cleanly with a timeout of 5 seconds
    

    And then exitChan <- struct{}{} in your handler/middleware when shutdown is required.

    See also: How to stop http.ListenAndServe()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?