Last active
February 29, 2024 18:06
-
-
Save KaiserWerk/34b8cff347a34856393e71e580b8f773 to your computer and use it in GitHub Desktop.
Golang: Webserver 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" | |
"fmt" | |
"net/http" | |
"os" | |
"os/signal" | |
"time" | |
) | |
func main() { | |
listenAddr := ":5000" | |
fmt.Printf("Server is ready to handle requests at %v\n", listenAddr) | |
// here you could also go with third party packages to create a router | |
router := http.NewServeMux() | |
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
w.WriteHeader(http.StatusOK) | |
w.Write([]byte("hello")) | |
}) | |
server := &http.Server{ | |
Addr: listenAddr, | |
Handler: router, | |
ReadTimeout: 5 * time.Second, | |
WriteTimeout: 10 * time.Second, | |
IdleTimeout: 15 * time.Second, | |
} | |
done := make(chan bool) | |
quit := make(chan os.Signal) | |
signal.Notify(quit, os.Interrupt) | |
go func() { | |
<-quit | |
fmt.Println("\nServer is shutting down...") | |
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) | |
defer cancel() | |
server.SetKeepAlivesEnabled(false) | |
if err := server.Shutdown(ctx); err != nil { | |
fmt.Printf("Could not gracefully shutdown the server: %v\n", err) | |
os.Exit(-1) | |
} | |
close(done) | |
}() | |
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { | |
fmt.Printf("Could not listen on %s: %v\n", listenAddr, err) | |
os.Exit(-1) | |
} | |
<-done | |
fmt.Println("Server stopped") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment