HTTP 연결이 정상적으로 완료되기 전에 프로그램이 종료되므로 HTTP 트랜잭션이 완료 될 때까지 기다린 다음 종료해야합니다. 다행히도 1.8 이후 http.Server
에는 Shutdown
method이 필요합니다.
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.
그래서, 일반적인 방법은 다음과 같습니다 핸들러/미들웨어에서 다음
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
그리고 exitChan <- struct{}{}
를 종료가 필요한 경우.
은 참조 : How to stop http.ListenAndServe()
예, 그것은 작동합니다. 그러나 Gin과 함께 사용하려면 추가 라인이 필요합니다. – sekrett
또한 5 초의 시간 초과가 없으며 즉시 종료되고 좋습니다. – sekrett