An Interest In:
Web News this Week
- May 1, 2024
- April 30, 2024
- April 29, 2024
- April 28, 2024
- April 27, 2024
- April 26, 2024
- April 25, 2024
February 26, 2022 05:00 pm GMT
Original Link: https://dev.to/clavinjune/golang-http-server-graceful-shutdown-4ke5
Golang HTTP Server Graceful Shutdown
package mainimport ( "context" "errors" "log" "net/http" "os" "os/signal" "syscall" "time")func createChannel() (chan os.Signal, func()) { stopCh := make(chan os.Signal, 1) signal.Notify(stopCh, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) return stopCh, func() { close(stopCh) }}func start(server *http.Server) { log.Println("application started") if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { panic(err) } else { log.Println("application stopped gracefully") }}func shutdown(ctx context.Context, server *http.Server) { ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() if err := server.Shutdown(ctx); err != nil { panic(err) } else { log.Println("application shutdowned") }}func main() { log.SetFlags(log.Lshortfile) s := &http.Server{} go start(s) stopCh, closeCh := createChannel() defer closeCh() log.Println("notified:", <-stopCh) shutdown(context.Background(), s)}
runtime:
$ go run main.gomain.go:24: application started^Cmain.go:50: notified: interrupt # ctrl+cmain.go:28: application stopped gracefullymain.go:39: application shutdowned$
Original Link: https://dev.to/clavinjune/golang-http-server-graceful-shutdown-4ke5
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To