-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.go
58 lines (47 loc) · 1.09 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
package runnable
import (
"context"
"fmt"
"net/http"
"time"
)
type httpServer struct {
baseWrapper
server *http.Server
shutdownTimeout time.Duration
}
// HTTPServer returns a runnable that runs a *http.Server.
func HTTPServer(server *http.Server) Runnable {
return &httpServer{baseWrapper{"httpserver", nil}, server, time.Second * 30}
}
func (r *httpServer) Run(ctx context.Context) error {
errChan := make(chan error)
go func() {
Log(r, "listening on %s", r.server.Addr)
errChan <- r.server.ListenAndServe()
}()
var err error
var shutdownErr error
select {
case <-ctx.Done():
Log(r, "shutdown")
shutdownErr = r.shutdown()
err = <-errChan
case err = <-errChan:
Log(r, "shutdown (err: %s)", err)
shutdownErr = r.shutdown()
}
if err == http.ErrServerClosed {
err = nil
}
if err == nil && shutdownErr != nil {
err = fmt.Errorf("server shutdown: %w", shutdownErr)
}
return err
}
func (r *httpServer) shutdown() error {
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, r.shutdownTimeout)
defer cancel()
return r.server.Shutdown(ctx)
}