Last active
August 14, 2020 04:38
-
-
Save chriswhitcombe/6a307a051c5c0366e6c3 to your computer and use it in GitHub Desktop.
Implementing a graceful shutdown of http that is docker compatible
This file contains 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 ( | |
"fmt" | |
"io" | |
"net/http" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
"github.com/braintree/manners" | |
) | |
func main() { | |
shutdown := make(chan int) | |
//create a notification channel to shutdown | |
sigChan := make(chan os.Signal, 1) | |
//start the http server | |
http.HandleFunc("/", hello) | |
server := manners.NewWithServer(&http.Server{Addr: ":80", Handler: nil}) | |
go func() { | |
server.ListenAndServe() | |
shutdown <- 1 | |
}() | |
//register for interupt (Ctrl+C) and SIGTERM (docker) | |
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) | |
go func() { | |
<-sigChan | |
fmt.Println("Shutting down...") | |
server.Close() | |
}() | |
<-shutdown | |
} | |
func hello(w http.ResponseWriter, r *http.Request) { | |
//pretend to do some work | |
time.Sleep(3000 * time.Millisecond) | |
io.WriteString(w, "Hello world!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment