-
Notifications
You must be signed in to change notification settings - Fork 0
/
gracefulshutdown.go
44 lines (39 loc) · 1.28 KB
/
gracefulshutdown.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
package httpx
import (
"context"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
// GracefulShutdownServerOnSignal shuts down the passed server
// gracefully after the process was notified with any of the passed signals.
// The server is guaranteed to shut down with the passed timeout after
// a signal. A timeout value of zero disables the timeout.
// If no signals are passed, then SIGHUP, SIGINT, SIGTERM will be used.
// If signalLog is not nil, then the received signal will be logged with it.
// If errorLog is not nil, then any errors from the server shutdown will be logged with it.
func GracefulShutdownServerOnSignal(server *http.Server, signalLog, errorLog Logger, timeout time.Duration, signals ...os.Signal) {
if len(signals) == 0 {
signals = []os.Signal{syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM}
}
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, signals...)
go func() {
sig := <-shutdown
if signalLog != nil {
signalLog.Printf("Received signal: %s", sig)
}
ctx := context.Background()
if timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
err := server.Shutdown(ctx)
if err != nil && errorLog != nil {
errorLog.Printf("http.Server shutdown error: %s", err)
}
}()
}