Skip to content

Commit 684a295

Browse files
committed
web-server: implement graceful shutdown
Rather than have a SIGINT or SIGTERM cause an immediate exit to the 'git-bundle-web-server' process, have it trigger a 'Shutdown()' on the hosted web server. Note that SIGKILL still forcibly stops the server, in case the shutdown gets stuck. Signed-off-by: Victoria Dye <[email protected]>
1 parent 7ed7e1c commit 684a295

File tree

1 file changed

+43
-4
lines changed

1 file changed

+43
-4
lines changed

cmd/git-bundle-web-server/main.go

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

33
import (
4+
"context"
45
"fmt"
56
"log"
67
"net/http"
78
"os"
9+
"os/signal"
810
"strings"
11+
"sync"
12+
"syscall"
913

1014
"github.com/github/git-bundle-server/internal/core"
1115
)
@@ -79,13 +83,48 @@ func serve(w http.ResponseWriter, r *http.Request) {
7983
w.Write(data)
8084
}
8185

82-
func main() {
86+
func createAndStartServer(address string, serverWaitGroup *sync.WaitGroup) *http.Server {
87+
// Create the HTTP server
88+
server := &http.Server{Addr: address}
89+
8390
// API routes
8491
http.HandleFunc("/", serve)
8592

93+
// Add to wait group
94+
serverWaitGroup.Add(1)
95+
96+
go func() {
97+
defer serverWaitGroup.Done()
98+
99+
// Return error unless it indicates graceful shutdown
100+
err := server.ListenAndServe()
101+
if err != http.ErrServerClosed {
102+
log.Fatal(err)
103+
}
104+
}()
105+
106+
fmt.Println("Server is running at address " + address)
107+
return server
108+
}
109+
110+
func main() {
111+
serverWaitGroup := &sync.WaitGroup{}
112+
113+
// Start the server asynchronously
86114
port := ":8080"
87-
fmt.Println("Server is running on port" + port)
115+
server := createAndStartServer(port, serverWaitGroup)
116+
117+
// Intercept interrupt signals
118+
c := make(chan os.Signal, 1)
119+
signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
120+
go func() {
121+
<-c
122+
fmt.Println("Starting graceful server shutdown...")
123+
server.Shutdown(context.Background())
124+
}()
125+
126+
// Wait for server to shut down
127+
serverWaitGroup.Wait()
88128

89-
// Start server on port specified above
90-
log.Fatal(http.ListenAndServe(port, nil))
129+
fmt.Println("Shutdown complete")
91130
}

0 commit comments

Comments
 (0)