Skip to content

Commit 9f8d162

Browse files
authored
Implement graceful shutdown (#78)
1 parent 62f0a57 commit 9f8d162

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

src/webserver.go

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66
"errors"
77
"log"
88
"net/http"
9+
"os"
10+
"os/signal"
911
"strconv"
1012
"strings"
1113
"time"
@@ -134,8 +136,33 @@ func runWebServer() {
134136
})
135137
})
136138

137-
// Start the router
138-
_ = router.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
139+
// build the http server
140+
server := &http.Server{
141+
Addr: ":8080", // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
142+
Handler: router,
143+
}
144+
145+
// graceful shutdown
146+
quit := make(chan os.Signal, 1)
147+
signal.Notify(quit, os.Interrupt)
148+
149+
// we run a go routine that will receive the shutdown input
150+
go func() {
151+
<-quit
152+
log.Println("Received shutdown input")
153+
if err := server.Close(); err != nil {
154+
log.Fatal("Server Close Error:", err)
155+
}
156+
}()
157+
158+
// run the server
159+
if err := server.ListenAndServe(); err != nil {
160+
if err == http.ErrServerClosed {
161+
log.Println("Server gracefully shut down")
162+
} else {
163+
log.Fatal("Server closed unexpectedly")
164+
}
165+
}
139166
}
140167

141168
// Character godoc

0 commit comments

Comments
 (0)