Created
December 29, 2020 17:49
-
-
Save nkreiger/07310666b85c9146fe53543c16085ffa to your computer and use it in GitHub Desktop.
graceful listen and serve
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
func GracefullyListenAndServe(ctx context.Context, servePort string, rtr *mux.Router) { | |
http.Handle("/", rtr) | |
h := &http.Server{ | |
Addr: fmt.Sprintf(":%v", servePort), | |
Handler: handlers.CORS()(rtr), | |
} | |
sig := make(chan os.Signal, 1) | |
signal.Notify(sig, os.Interrupt) | |
signal.Notify(sig, syscall.SIGTERM) | |
go func() { | |
log.Printf("serving on port: %v", servePort) | |
if err := h.ListenAndServe(); err != nil { | |
log.Fatalf("%v", err) | |
} | |
}() | |
// wait for signal to end | |
<-sig | |
log.Println("Shutting down server...") | |
_ = h.Shutdown(ctx) | |
log.Println("server gracefully shutdown") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment