-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterrupt.go
50 lines (41 loc) · 1.17 KB
/
interrupt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package server
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"golang.org/x/term"
)
// Interrupt is a graceful interrupt + signal handler for an HTTP server.
func Interrupt(ctx context.Context, cancel context.CancelFunc, server *http.Server) {
// Listen for syscall signals for process to interrupt/quit
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
<-interrupt
if term.IsTerminal(int(os.Stdout.Fd())) {
fmt.Print("\r")
}
slog.DebugContext(ctx, "Initializing Server Shutdown ...")
// Shutdown signal with grace period of 30 seconds
shutdown, timeout := context.WithTimeout(ctx, 30*time.Second)
defer timeout()
go func() {
<-shutdown.Done()
if errors.Is(shutdown.Err(), context.DeadlineExceeded) {
slog.Log(ctx, slog.LevelError, "Graceful Server Shutdown Timeout - Forcing an Exit ...")
os.Exit(99)
}
}()
// Trigger graceful shutdown
if e := server.Shutdown(shutdown); e != nil {
slog.ErrorContext(ctx, "Exception During Server Shutdown", slog.String("error", e.Error()))
}
cancel()
}()
}