Implement graceful shutdown

This commit is contained in:
Thorben Günther 2023-07-17 16:39:16 +02:00
parent 4fcb1f952c
commit 913a076c52
No known key found for this signature in database
GPG key ID: 415CD778D8C5AFED

35
main.go
View file

@ -2,6 +2,7 @@
package main
import (
"context"
"crypto/sha512"
"crypto/subtle"
_ "embed"
@ -11,7 +12,9 @@ import (
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"git.xenrox.net/~xenrox/go-log"
@ -411,11 +414,15 @@ func (br *bridge) basicAuthMiddleware(handler http.HandlerFunc) http.HandlerFunc
}
}
func (br *bridge) runCleanup() {
func (br *bridge) runCleanup(ctx context.Context) {
for {
time.Sleep(br.cfg.Cache.CleanupInterval)
select {
case <-time.After(br.cfg.Cache.CleanupInterval):
br.logger.Info("Pruning cache")
br.cache.Cleanup()
case <-ctx.Done():
return
}
}
}
@ -442,6 +449,9 @@ func main() {
logger.Errorf("Failed to parse logging level: %v", err)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
client := &httpClient{&http.Client{Timeout: time.Second * 3}}
c, err := cache.NewCache(cfg.Cache)
@ -468,7 +478,24 @@ func main() {
}
if _, ok := c.(*cache.MemoryCache); ok {
go bridge.runCleanup()
go bridge.runCleanup(ctx)
}
go func() {
err = httpServer.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
logger.Fatalf("Failed to start HTTP server: %v", err)
}
}()
<-ctx.Done()
stop()
httpShutdownContext, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = httpServer.Shutdown(httpShutdownContext)
if err != nil {
logger.Errorf("Failed to shutdown HTTP server: %v", err)
}
logger.Fatal(httpServer.ListenAndServe())
}