Created
August 6, 2018 10:50
-
-
Save wayneashleyberry/ecf6c40d80e95ab299f0c0a772b4c554 to your computer and use it in GitHub Desktop.
Go http server with graceful shutdown
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"log" | |
"net/http" | |
"os" | |
"os/signal" | |
"syscall" | |
) | |
func main() { | |
var srv http.Server | |
idleConnsClosed := make(chan struct{}) | |
go func() { | |
sigint := make(chan os.Signal, 1) | |
// interrupt signal sent from terminal | |
signal.Notify(sigint, os.Interrupt) | |
// sigterm signal sent from kubernetes | |
signal.Notify(sigint, syscall.SIGTERM) | |
<-sigint | |
// We received an interrupt signal, shut down. | |
if err := srv.Shutdown(context.Background()); err != nil { | |
// Error from closing listeners, or context timeout: | |
log.Printf("HTTP server Shutdown: %v", err) | |
} | |
close(idleConnsClosed) | |
}() | |
if err := srv.ListenAndServe(); err != http.ErrServerClosed { | |
// Error starting or closing listener: | |
log.Printf("HTTP server ListenAndServe: %v", err) | |
} | |
<-idleConnsClosed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unfortunately,
srv.Shutdown
cannot graceful shutdown for hijack connection of WebSocket. Do we have any solution for it?