2017-11-30 5 views
-1

os.Exit(0) HTTP 요청이 완전히 끝난 후 애플리케이션을 종료해야합니다. 내 응용 프로그램은 다른 서버에 업그레이드가 필요한지 묻습니다. 따라서 재부팅을 통한 자체 업그레이드 수행을 위해 종료해야하지만 현재 HTTP 요청을 중단하고 싶지는 않습니다.Gin 프레임 워크에서 애프터 콜백을 추가하는 방법

c.Next() 후에 미들웨어를 종료하거나 처리기 기능이 끝나면 브라우저에서 오류 : localhost didn’t send any data이 표시됩니다.

어떻게 수행 할 수 있습니까?

답변

2

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

+0

예, 그것은 작동합니다. 그러나 Gin과 함께 사용하려면 추가 라인이 필요합니다. – sekrett

+0

또한 5 초의 시간 초과가 없으며 즉시 종료되고 좋습니다. – sekrett