-
Notifications
You must be signed in to change notification settings - Fork 110
/
run.go
70 lines (60 loc) · 1.67 KB
/
run.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
// Copyright 2021 ChainSafe Systems (ON)
// SPDX-License-Identifier: LGPL-3.0-only
package httpserver
import (
"context"
"errors"
"net"
"net/http"
)
// Run runs the HTTP server until ctx is canceled.
// The done channel has an error written to when the HTTP server
// is terminated, and can be nil or not nil.
func (s *Server) Run(ctx context.Context, ready chan<- struct{}, done chan<- error) {
server := http.Server{
Addr: s.address,
Handler: s.handler,
ReadHeaderTimeout: s.optional.readHeaderTimeout,
ReadTimeout: s.optional.readTimeout,
}
crashed := make(chan struct{})
shutdownDone := make(chan struct{})
go func() {
defer close(shutdownDone)
select {
case <-ctx.Done():
case <-crashed:
return
}
s.logger.Warn(s.name + " http server shutting down: " + ctx.Err().Error())
shutdownCtx, cancel := context.WithTimeout(context.Background(),
s.optional.shutdownTimeout)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
s.logger.Error(s.name + " http server failed shutting down within " +
s.optional.shutdownTimeout.String())
}
}()
listener, err := net.Listen("tcp", s.address)
if err != nil {
close(s.addressSet)
close(crashed) // stop shutdown goroutine
<-shutdownDone
done <- err
return
}
s.address = listener.Addr().String()
close(s.addressSet)
// note: no further write so no need to mutex
s.logger.Info(s.name + " http server listening on " + s.address)
close(ready)
err = server.Serve(listener)
if err != nil && !errors.Is(ctx.Err(), context.Canceled) {
// server crashed
close(crashed) // stop shutdown goroutine
} else {
err = nil
}
<-shutdownDone
done <- err
}