-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathconfig.go
More file actions
326 lines (282 loc) · 10.5 KB
/
Copy pathconfig.go
File metadata and controls
326 lines (282 loc) · 10.5 KB
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package httpserver
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log/slog"
"math"
"net"
"net/http"
"runtime/debug"
"slices"
"strconv"
"sync"
"time"
"github.com/julienschmidt/httprouter"
"github.com/tecnickcom/nurago/pkg/httputil"
"github.com/tecnickcom/nurago/pkg/ipify"
"github.com/tecnickcom/nurago/pkg/profiling"
"github.com/tecnickcom/nurago/pkg/random"
"github.com/tecnickcom/nurago/pkg/redact"
"github.com/tecnickcom/nurago/pkg/traceid"
)
// timeoutMessage is the message used for timeout responses.
const timeoutMessage = "TIMEOUT"
// RedactFn redacts sensitive values from logged byte payloads and returns a redacted string.
type RedactFn func(b []byte) string
// IndexHandlerFunc builds an index handler from the registered route list.
type IndexHandlerFunc func([]Route) http.HandlerFunc
// GetPublicIPFunc resolves the service public IP address.
type GetPublicIPFunc func(context.Context) (string, error)
// GetPublicIPDefaultFunc returns the GetPublicIP function for a default ipify client.
func GetPublicIPDefaultFunc() GetPublicIPFunc {
c, _ := ipify.New() // no errors are returned with default values
return c.GetPublicIP
}
// config contains the configuration for the HTTP server.
type config struct {
router *httprouter.Router
serverAddr string
traceIDHeaderName string
requestTimeout time.Duration
serverReadHeaderTimeout time.Duration
serverReadTimeout time.Duration
serverWriteTimeout time.Duration
serverIdleTimeout time.Duration
serverMaxHeaderBytes int
maxRequestBodyBytes int64
shutdownTimeout time.Duration
tlsConfig *tls.Config
defaultEnabledRoutes []DefaultRoute
indexHandlerFunc IndexHandlerFunc
ipHandlerFunc http.HandlerFunc
metricsHandlerFunc http.HandlerFunc
pingHandlerFunc http.HandlerFunc
pprofHandlerFunc http.HandlerFunc
statusHandlerFunc http.HandlerFunc
notFoundHandlerFunc http.HandlerFunc
methodNotAllowedHandlerFunc http.HandlerFunc
panicHandlerFunc http.HandlerFunc
redactFn RedactFn
middleware []MiddlewareFn
disableDefaultRouteLogger map[DefaultRoute]bool
disableRouteLogger bool
disableNotFoundLogger bool
disableMethodNotAllowedLogger bool
logger *slog.Logger
shutdownWaitGroup *sync.WaitGroup
shutdownSignalChan chan struct{}
httpresp *httputil.HTTPResp
rnd *random.Rnd
}
// defaultConfig returns the default configuration for the HTTP server.
func defaultConfig() *config {
logger := slog.Default()
cfg := &config{
router: httprouter.New(),
serverAddr: ":8017",
traceIDHeaderName: traceid.DefaultHeader,
serverReadHeaderTimeout: 1 * time.Minute,
serverReadTimeout: 1 * time.Minute,
serverWriteTimeout: 1 * time.Minute,
serverIdleTimeout: 1 * time.Minute,
shutdownTimeout: 30 * time.Second,
defaultEnabledRoutes: nil,
redactFn: redact.Default().BytesToString,
middleware: []MiddlewareFn{},
disableDefaultRouteLogger: make(map[DefaultRoute]bool, len(allDefaultRoutes())),
logger: logger,
shutdownWaitGroup: &sync.WaitGroup{},
shutdownSignalChan: make(chan struct{}),
httpresp: httputil.NewHTTPResp(logger),
rnd: random.New(nil),
}
cfg.pprofHandlerFunc = profiling.PProfHandler
cfg.indexHandlerFunc = cfg.defaultIndexHandler
cfg.ipHandlerFunc = cfg.defaultIPHandler(GetPublicIPDefaultFunc())
cfg.metricsHandlerFunc = cfg.notImplementedHandler()
cfg.pingHandlerFunc = cfg.defaultPingHandler()
cfg.statusHandlerFunc = cfg.defaultStatusHandler()
cfg.notFoundHandlerFunc = cfg.defaultNotFoundHandlerFunc()
cfg.methodNotAllowedHandlerFunc = cfg.defaultMethodNotAllowedHandlerFunc()
cfg.panicHandlerFunc = cfg.defaultPanicHandlerFunc()
return cfg
}
// isIndexRouteEnabled checks if the index route is enabled in the configuration.
func (c *config) isIndexRouteEnabled() bool {
return slices.Contains(c.defaultEnabledRoutes, IndexRoute)
}
// validateAddr checks if a http server bind address is valid.
// The host part may be empty, a hostname, an IPv4 or a bracketed IPv6 address
// (e.g. ":8080", "localhost:8080", "0.0.0.0:8080", "[::1]:8080").
func validateAddr(addr string) error {
addrErr := fmt.Errorf("invalid http server address: %s", addr)
_, port, err := net.SplitHostPort(addr)
if err != nil {
return addrErr
}
portInt, err := strconv.Atoi(port)
if err != nil {
return addrErr
}
// Port 0 is valid: it asks the operating system for an ephemeral port.
if portInt < 0 || portInt > math.MaxUint16 {
return addrErr
}
return nil
}
// commonMiddleware returns the common middleware for all routes.
func (c *config) commonMiddleware(noRouteLogger bool, rTimeout time.Duration) []MiddlewareFn {
middleware := []MiddlewareFn{}
// The body-size guard is outermost so it wraps the original response
// writer (enabling net/http's request-too-large connection handling) and
// caps even the debug request dump performed by the logger middleware.
if c.maxRequestBodyBytes > 0 {
maxBodyMiddlewareFn := func(_ MiddlewareArgs, next http.Handler) http.Handler {
return http.MaxBytesHandler(next, c.maxRequestBodyBytes)
}
middleware = append(middleware, maxBodyMiddlewareFn)
}
if !c.disableRouteLogger && !noRouteLogger {
middleware = append(middleware, LoggerMiddlewareFn)
}
// A positive per-route timeout overrides the global one; a negative value
// (e.g. DisableTimeout) disables the timeout for the route entirely.
timeout := c.requestTimeout
if rTimeout != 0 {
timeout = rTimeout
}
if timeout > 0 {
timeoutMiddlewareFn := func(_ MiddlewareArgs, next http.Handler) http.Handler {
return http.TimeoutHandler(next, timeout, timeoutMessage)
}
middleware = append(middleware, timeoutMiddlewareFn)
}
return append(middleware, c.middleware...)
}
// mwArgs builds the MiddlewareArgs shared by every route and default handler.
func (c *config) mwArgs(method, path, description string) MiddlewareArgs {
return MiddlewareArgs{
Method: method,
Path: path,
Description: description,
TraceIDHeaderName: c.traceIDHeaderName,
RedactFunc: c.redactFn,
Logger: c.logger,
Rnd: c.rnd,
}
}
// setRouter sets the router's default handlers if they are not already set.
func (c *config) setRouter() {
if c.router.NotFound == nil {
c.router.NotFound = ApplyMiddleware(
c.mwArgs("", "404", http.StatusText(http.StatusNotFound)),
c.notFoundHandlerFunc,
c.commonMiddleware(c.disableNotFoundLogger, 0)...,
)
}
if c.router.MethodNotAllowed == nil {
c.router.MethodNotAllowed = ApplyMiddleware(
c.mwArgs("", "405", http.StatusText(http.StatusMethodNotAllowed)),
c.methodNotAllowedHandlerFunc,
c.commonMiddleware(c.disableMethodNotAllowedLogger, 0)...,
)
}
if c.router.PanicHandler == nil {
c.router.PanicHandler = c.newPanicHandler(c.commonMiddleware(false, 0))
}
}
// newPanicHandler builds the router panic handler. Panics carrying
// http.ErrAbortHandler are re-raised so net/http can abort the connection
// silently (its documented contract); all other panics are logged with a stack
// trace and answered through the configured panic handler.
func (c *config) newPanicHandler(middleware []MiddlewareFn) func(http.ResponseWriter, *http.Request, any) {
handler := ApplyMiddleware(
c.mwArgs("", "500", http.StatusText(http.StatusInternalServerError)),
c.panicHandlerFunc,
middleware...,
)
return func(w http.ResponseWriter, r *http.Request, p any) {
perr, ok := p.(error)
if ok && errors.Is(perr, http.ErrAbortHandler) {
panic(p)
}
c.logger.With(
slog.Any("error", p),
slog.String("stacktrace", string(debug.Stack())),
).Error("panic")
handler.ServeHTTP(w, r)
}
}
// defaultIndexHandler returns the default index handler.
// The rendered list contains every bound route except the index route itself.
func (c *config) defaultIndexHandler(routes []Route) http.HandlerFunc {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
data := &Index{Routes: routes}
c.httpresp.SendJSON(r.Context(), w, http.StatusOK, data)
},
)
}
// defaultIPHandler returns the default /ip handler.
func (c *config) defaultIPHandler(fn GetPublicIPFunc) http.HandlerFunc {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
status := http.StatusOK
ip, err := fn(r.Context())
if err != nil {
status = http.StatusFailedDependency
}
c.httpresp.SendText(r.Context(), w, status, ip)
},
)
}
// defaultPingHandler returns the default /ping handler.
func (c *config) defaultPingHandler() http.HandlerFunc {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
c.httpresp.SendStatus(r.Context(), w, http.StatusOK)
},
)
}
// defaultStatusHandler returns the default /status handler.
func (c *config) defaultStatusHandler() http.HandlerFunc {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
c.httpresp.SendStatus(r.Context(), w, http.StatusOK)
},
)
}
// notImplementedHandler returns a 501 Not Implemented response.
func (c *config) notImplementedHandler() http.HandlerFunc {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
c.httpresp.SendStatus(r.Context(), w, http.StatusNotImplemented)
},
)
}
// defaultNotFoundHandlerFunc returns the default 404 Not Found handler function.
func (c *config) defaultNotFoundHandlerFunc() http.HandlerFunc {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
c.httpresp.SendStatus(r.Context(), w, http.StatusNotFound)
},
)
}
// defaultMethodNotAllowedHandlerFunc returns the default 405 Method Not Allowed handler function.
func (c *config) defaultMethodNotAllowedHandlerFunc() http.HandlerFunc {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
c.httpresp.SendStatus(r.Context(), w, http.StatusMethodNotAllowed)
},
)
}
// defaultPanicHandlerFunc returns the default panic handler function.
func (c *config) defaultPanicHandlerFunc() http.HandlerFunc {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
c.httpresp.SendStatus(r.Context(), w, http.StatusInternalServerError)
},
)
}