/
gracehttp.go
105 lines (88 loc) · 2.64 KB
/
gracehttp.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
93
94
95
96
97
98
99
100
101
102
103
104
105
package gracehttp
import (
"context"
"log"
"net"
"net/http"
"os"
"os/signal"
"time"
"github.com/pkg/errors"
"golang.org/x/net/http2"
)
// WaitForInterrupt blocks until an interrupt signal is received.
func WaitForInterrupt() os.Signal {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
return <-sig
}
// Server is the wrapper around a regular net/http server. It is not
// thread-safe, and must never be shared across goroutines.
type Server struct {
*http.Server
}
// ListenAndServeAsync listens and serves the given address. The returned
// server can be used to gracefully shut down the server.
func ListenAndServeAsync(addr string, h http.Handler) *Server {
s := MustServer(addr, h)
if err := s.ListenAndServeAsync(context.Background()); err != nil {
log.Fatalln("failed to listen and serve:", err)
}
return s
}
// MustServer creates a new server and panics if it fails.
func MustServer(addr string, h http.Handler) *Server {
s, err := NewServer(addr, h)
if err != nil {
log.Fatalln("failed to create gracehttp server:", err)
}
return s
}
// NewServer creates a new graceful server instance with defaults.
func NewServer(addr string, h http.Handler) (*Server, error) {
h1 := http.Server{
Addr: addr,
Handler: h,
}
h2 := http2.Server{
MaxHandlers: 10240,
MaxConcurrentStreams: 4096,
}
return NewCustomServer(&h1, &h2)
}
// NewCustomServer creates a new graceful server instance from the given
// configs. If h2 is nil, then HTTP2 is not forced.
func NewCustomServer(h1 *http.Server, h2 *http2.Server) (*Server, error) {
if h2 != nil {
if err := http2.ConfigureServer(h1, h2); err != nil {
return nil, errors.Wrap(err, "failed to configure http2")
}
}
return &Server{Server: h1}, nil
}
// ListenAndServe listens to and serves the server's address. The context is
// used for timing out the initial listen.
func (s *Server) ListenAndServe(ctx context.Context) error {
l, err := ListenAddrCfg(ctx, s.Addr, net.ListenConfig{})
if err != nil {
return err
}
return s.Server.Serve(l)
}
// ListenAndServeAsync listens to the server's address and serves in a
// background goroutine. The context is used for timing out the initial listen.
func (s *Server) ListenAndServeAsync(ctx context.Context) error {
l, err := ListenAddrCfg(ctx, s.Addr, net.ListenConfig{})
if err != nil {
return err
}
go s.Server.Serve(l)
return nil
}
// ShutdownTimeout is a convenient function to allow graceful shutdown for the
// given duration.
func (s *Server) ShutdownTimeout(timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return s.Server.Shutdown(ctx)
}