Skip to content

Commit 6014080

Browse files
committed
Graceful shutdown
1 parent 36b4093 commit 6014080

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

server/cache.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ func (c *Cache) Init(collection *Collection, rebuildCache bool) error {
9191

9292
// Release all caching resources
9393
func (c *Cache) End() error {
94+
c.FinishFlush()
9495
c.mem.Purge()
9596
return c.store.Close()
9697
}

server/main.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
package main
22

33
import (
4+
"context"
45
"errors"
56
"log"
67
"net/http"
78
"net/url"
9+
"os"
10+
"os/signal"
811
"path"
912
"strconv"
1013
"strings"
14+
"time"
1115

1216
"github.com/labstack/echo/v4"
1317
"github.com/labstack/echo/v4/middleware"
@@ -350,5 +354,22 @@ func main() {
350354

351355
// Start server
352356
log.Println("Starting server: http://" + serverAddr)
353-
e.Logger.Fatal(e.Start(serverAddr))
357+
go func() {
358+
if err := e.Start(serverAddr); err != nil && err != http.ErrServerClosed {
359+
e.Logger.Fatal("shutting down the server")
360+
}
361+
}()
362+
363+
// Wait for interrupt signal to gracefully shutdown the server with a timeout of 10 seconds.
364+
// Use a buffered channel to avoid missing signals as recommended for signal.Notify
365+
log.Println("Press Ctrl-C to stop the server")
366+
quit := make(chan os.Signal, 1)
367+
signal.Notify(quit, os.Interrupt)
368+
<-quit
369+
log.Println("Shutting down the server...")
370+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
371+
defer cancel()
372+
if err := e.Shutdown(ctx); err != nil {
373+
e.Logger.Fatal(err)
374+
}
354375
}

0 commit comments

Comments
 (0)