Created
June 30, 2017 18:10
-
-
Save kpurdon/f2965602b2f55a0d8199e5418bd4aacb to your computer and use it in GitHub Desktop.
golang graceful server shutdown example
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 ( | |
"context" | |
"flag" | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
"os/signal" | |
"time" | |
) | |
const ( | |
service = "fooapi" | |
) | |
var ( | |
port = flag.Int("port", 3333, "http port to listen on") | |
shutdownTimeout = flag.Duration("shutdown-timeout", 10*time.Second, | |
"shutdown timeout (5s,5m,5h) before connections are cancelled") | |
) | |
func main() { | |
flag.Parse() | |
mux := http.NewServeMux() | |
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
w.WriteHeader(200) | |
}) | |
srv := &http.Server{ | |
Addr: fmt.Sprintf(":%d", *port), | |
Handler: mux, | |
} | |
stop := make(chan os.Signal) | |
signal.Notify(stop, os.Interrupt) | |
go func() { | |
log.Printf("%s listening on 0.0.0.0:%d with %v timeout", service, *port, *shutdownTimeout) | |
if err := srv.ListenAndServe(); err != nil { | |
if err != http.ErrServerClosed { | |
log.Fatal(err) | |
} | |
} | |
}() | |
<-stop | |
log.Printf("%s shutting down ...\n", service) | |
ctx, cancel := context.WithTimeout(context.Background(), *shutdownTimeout) | |
defer cancel() | |
if err := srv.Shutdown(ctx); err != nil { | |
log.Fatal(err) | |
} | |
log.Printf("%s down\n", service) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi,
I created a module which wraps this functionality: https://github.com/pseidemann/finish