-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.go
67 lines (55 loc) · 1.63 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
package main
import (
"context"
"fmt"
"net/http"
"os/signal"
"syscall"
"time"
"github.com/chinmina/chinmina-bridge/internal/config"
"github.com/rs/zerolog/log"
)
type AuthServer interface {
ListenAndServe() error
Shutdown(ctx context.Context) error
}
func serveHTTP(serverCfg config.ServerConfig, server AuthServer) error {
serverCtx := context.Background()
// capture shutdown signals to allow for graceful shutdown
ctx, stop := signal.NotifyContext(serverCtx,
syscall.SIGINT, syscall.SIGTERM,
)
defer stop()
// Start the server in a new goroutine
serverErr := make(chan error, 1)
go func() {
log.Info().Int("port", serverCfg.Port).Msg("starting server")
serverErr <- server.ListenAndServe()
}()
var startupError error
select {
case err := <-serverErr:
// Error when starting HTTP server.
if err != nil && err != http.ErrServerClosed {
log.Error().Err(err).Msg("failed to start server")
}
// save this error to return, keep processing shutdown sequence
startupError = err
case <-ctx.Done():
log.Info().Msg("server shutdown requested")
// Stop receiving signal notifications as soon as possible.
stop()
}
// Gracefully stop the server, allowing a configurable amount of time for
// in-flight requests to complete
shutdownTimeout := time.Duration(serverCfg.ShutdownTimeoutSeconds) * time.Second
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
err := server.Shutdown(ctx)
if err != nil {
return fmt.Errorf("server shutdown failed: %w", err)
}
log.Info().Msg("server shutdown complete")
// if startup failed the error is returned
return startupError
}