Skip to content

Commit 15fa0be

Browse files
authored
Merge pull request #46 from adrienkohlbecker/graceful-shutdown
Gracefully shutdown http server
2 parents 2ed51f4 + f31457b commit 15fa0be

1 file changed

Lines changed: 25 additions & 2 deletions

File tree

main.go

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
package main
22

33
import (
4-
"flag"
4+
"context"
55
"embed"
6+
"errors"
7+
"flag"
68
"io/fs"
79
"log"
810
"net"
911
"net/http"
1012
"os"
13+
"os/signal"
1114
"path/filepath"
1215
"strconv"
16+
"syscall"
1317
"time"
1418

1519
"github.com/NYTimes/gziphandler"
@@ -113,7 +117,26 @@ func setupWebServer() {
113117
ReadTimeout: 15 * time.Second,
114118
}
115119

116-
log.Fatal(srv.ListenAndServe())
120+
go func() {
121+
err := srv.ListenAndServe()
122+
if !errors.Is(err, http.ErrServerClosed) {
123+
log.Fatalf("HTTP server error: %v", err)
124+
}
125+
log.Println("Stopped serving new connections.")
126+
}()
127+
128+
sigChan := make(chan os.Signal, 1)
129+
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
130+
<-sigChan
131+
132+
shutdownCtx, shutdownRelease := context.WithTimeout(context.Background(), 10*time.Second)
133+
defer shutdownRelease()
134+
135+
err = srv.Shutdown(shutdownCtx)
136+
if err != nil {
137+
log.Fatalf("HTTP shutdown error: %v", err)
138+
}
139+
log.Println("Graceful shutdown complete.")
117140

118141
}
119142

0 commit comments

Comments
 (0)