-
Notifications
You must be signed in to change notification settings - Fork 249
/
httpserver.go
168 lines (154 loc) · 4.78 KB
/
httpserver.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// Copyright 2020-2022 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package httpserver
import (
"context"
"crypto/tls"
"net"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"golang.org/x/sync/errgroup"
)
const (
// DefaultShutdownTimeout is the default shutdown timeout.
DefaultShutdownTimeout = 10 * time.Second
// DefaultReadHeaderTimeout is the default read header timeout.
DefaultReadHeaderTimeout = 30 * time.Second
// DefaultIdleTimeout is the amount of time an HTTP/2 connection can be idle.
DefaultIdleTimeout = 3 * time.Minute
)
type runner struct {
shutdownTimeout time.Duration
readHeaderTimeout time.Duration
tlsConfig *tls.Config
walkFunc chi.WalkFunc
}
// RunOption is an option for a new Run.
type RunOption func(*runner)
// RunWithShutdownTimeout returns a new RunOption that uses the given shutdown timeout.
//
// The default is to use DefaultShutdownTimeout.
// If shutdownTimeout is 0, no graceful shutdown will be performed.
func RunWithShutdownTimeout(shutdownTimeout time.Duration) RunOption {
return func(runner *runner) {
runner.shutdownTimeout = shutdownTimeout
}
}
// RunWithReadHeaderTimeout returns a new RunOption that uses the given read header timeout.
//
// The default is to use DefaultReadHeaderTimeout.
// If readHeaderTimeout is 0, no read header timeout will be used.
func RunWithReadHeaderTimeout(readHeaderTimeout time.Duration) RunOption {
return func(runner *runner) {
runner.readHeaderTimeout = readHeaderTimeout
}
}
// RunWithTLSConfig returns a new RunOption that uses the given tls.Config.
//
// The default is to use no TLS.
func RunWithTLSConfig(tlsConfig *tls.Config) RunOption {
return func(runner *runner) {
runner.tlsConfig = tlsConfig
}
}
// RunWithWalkFunc returns a new RunOption that runs chi.Walk to walk the
// handler after all middlewares and routes have been mounted, but before the
// server is started.
// The walkFunc will only be called if the handler passed to Run is a
// chi.Routes.
func RunWithWalkFunc(walkFunc chi.WalkFunc) RunOption {
return func(runner *runner) {
runner.walkFunc = walkFunc
}
}
// Run will start a HTTP server listening on the provided listener and
// serving the provided handler. This call is blocking and the run
// is cancelled when the input context is cancelled, the listener is
// closed upon return.
//
// The Run function can be configured further by passing a variety of options.
func Run(
ctx context.Context,
logger *zap.Logger,
listener net.Listener,
handler http.Handler,
options ...RunOption,
) error {
s := &runner{
shutdownTimeout: DefaultShutdownTimeout,
readHeaderTimeout: DefaultReadHeaderTimeout,
}
for _, option := range options {
option(s)
}
stdLogger, err := zap.NewStdLogAt(logger.Named("httpserver"), zap.ErrorLevel)
if err != nil {
return err
}
httpServer := &http.Server{
Handler: handler,
ReadHeaderTimeout: s.readHeaderTimeout,
ErrorLog: stdLogger,
TLSConfig: s.tlsConfig,
}
if s.tlsConfig == nil {
httpServer.Handler = h2c.NewHandler(handler, &http2.Server{
IdleTimeout: DefaultIdleTimeout,
})
}
if s.walkFunc != nil {
routes, ok := handler.(chi.Routes)
if ok {
if err := chi.Walk(routes, s.walkFunc); err != nil {
return err
}
}
}
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
return httpServe(httpServer, listener)
})
eg.Go(func() error {
<-ctx.Done()
start := time.Now()
logger.Info("shutdown_starting", zap.Duration("shutdown_timeout", s.shutdownTimeout))
defer logger.Info("shutdown_finished", zap.Duration("duration", time.Since(start)))
if s.shutdownTimeout != 0 {
ctx, cancel := context.WithTimeout(context.Background(), s.shutdownTimeout)
defer cancel()
return httpServer.Shutdown(ctx)
}
return httpServer.Close()
})
logger.Info(
"starting",
zap.String("address", listener.Addr().String()),
zap.Duration("shutdown_timeout", s.shutdownTimeout),
zap.Bool("tls", s.tlsConfig != nil),
)
if err := eg.Wait(); err != http.ErrServerClosed {
return err
}
return nil
}
func httpServe(httpServer *http.Server, listener net.Listener) error {
if httpServer.TLSConfig != nil {
return httpServer.ServeTLS(listener, "", "")
}
return httpServer.Serve(listener)
}