This repository has been archived by the owner on Nov 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
92 lines (68 loc) · 1.58 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
81
82
83
84
85
86
87
88
89
90
91
92
// SPDX-FileCopyrightText: 2023 Iván Szkiba
//
// SPDX-License-Identifier: MIT
package muxpress
import (
"context"
"errors"
"net"
"net/http"
"time"
"github.com/sirupsen/logrus"
)
type server struct {
logger logrus.FieldLogger
context func() context.Context
stopCh chan struct{}
}
func newServer(context func() context.Context, logger logrus.FieldLogger) *server {
srv := &server{
context: context,
logger: logger,
stopCh: make(chan struct{}),
}
return srv
}
func (s *server) serve(listener net.Listener, handler http.Handler) {
srv := new(http.Server)
srv.Handler = handler
errCh := make(chan error)
go func() {
s.logger.Debug("server started")
errCh <- srv.Serve(listener)
}()
var err error
ctx := s.context()
select {
case <-s.stopCh:
break
case <-ctx.Done():
break
case err = <-errCh:
break
}
if err != nil {
s.logger.WithError(err).Error("server aborted")
return
}
ctx, cancel := context.WithTimeout(ctx, shutdownTimeout)
defer cancel()
if err := srv.Shutdown(ctx); !errors.Is(err, context.DeadlineExceeded) && !errors.Is(err, context.Canceled) {
s.logger.WithError(err).Errorf("server shutdown failed")
}
s.logger.Debug("server stopped")
}
func (s *server) listenAndServe(addr string, handler http.Handler) (*net.TCPAddr, error) {
listener, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
s.stopCh = make(chan struct{})
go s.serve(listener, handler)
a, _ := listener.Addr().(*net.TCPAddr)
return a, nil
}
func (s *server) shutdown() {
s.stopCh <- struct{}{}
}
const shutdownTimeout = 500 * time.Millisecond