Skip to content

Instantly share code, notes, and snippets.

@macedo
Created June 19, 2024 18:10
Show Gist options
  • Save macedo/3798409229c8694d28d33db386410ee2 to your computer and use it in GitHub Desktop.
Save macedo/3798409229c8694d28d33db386410ee2 to your computer and use it in GitHub Desktop.
server gracefull shutdown
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
server := &http.Server{
Addr: ":8080",
}
http.Handle("/", http.FileServer(http.Dir("./public")))
go func() {
if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("HTTP server error: %v", err)
}
log.Println("Stopped serving new connections.")
}()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
shutdownCtx, shutdownRelease := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownRelease()
if err := server.Shutdown(shutdownCtx); err != nil {
log.Fatalf("HTTP shutdown error: %v", err)
}
log.Println("Graceful shutdown complete.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment