-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
80 lines (69 loc) · 1.46 KB
/
server.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package snet
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"sync"
"time"
)
// ListenAndServe starts the server and listens for signals to shut down the server.
func ListenAndServe(
ctx context.Context,
server *http.Server,
logger *slog.Logger,
signals ...os.Signal,
) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var (
wg sync.WaitGroup
errorsCh = make(chan error, 2)
)
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
select {
case <-ctx.Done():
logger.Info("start server: ctx canceled")
return
default:
}
logger.Info("server listen and serve", slog.String("Addr", server.Addr))
if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
logger.Error("server listen and serve", "error", err)
errorsCh <- err
}
}()
// Run signal handler
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
c := make(chan os.Signal)
signal.Notify(c, signals...)
select {
case <-ctx.Done():
case sig := <-c:
logger.Warn("received signal", slog.String("signal", sig.String()))
}
ctx, cancel = context.WithTimeout(ctx, 10*time.Second)
defer cancel()
logger.Warn("shutting down server")
if err := server.Shutdown(ctx); err != nil {
logger.Error("server shutdown", "error", err)
errorsCh <- err
}
logger.Warn("shut down")
}()
wg.Wait()
close(errorsCh)
var err error = nil
for e := range errorsCh {
err = errors.Join(err, e)
}
return err
}