-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathconfig.go
More file actions
306 lines (266 loc) · 8.97 KB
/
config.go
File metadata and controls
306 lines (266 loc) · 8.97 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
package httpserver
import (
"context"
"crypto/tls"
"fmt"
"log/slog"
"math"
"net/http"
"runtime/debug"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/julienschmidt/httprouter"
"github.com/tecnickcom/gogen/pkg/httputil"
"github.com/tecnickcom/gogen/pkg/ipify"
"github.com/tecnickcom/gogen/pkg/profiling"
"github.com/tecnickcom/gogen/pkg/random"
"github.com/tecnickcom/gogen/pkg/redact"
"github.com/tecnickcom/gogen/pkg/traceid"
)
// timeoutMessage is the message used for timeout responses.
const timeoutMessage = "TIMEOUT"
// RedactFn is an alias for a redact function.
type RedactFn func(s string) string
// IndexHandlerFunc is a type alias for the route index function.
type IndexHandlerFunc func([]Route) http.HandlerFunc
// GetPublicIPFunc is a type alias for function to get public IP of the service.
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
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
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,
shutdownTimeout: 30 * time.Second,
defaultEnabledRoutes: nil,
redactFn: redact.HTTPData,
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.
func validateAddr(addr string) error {
addrErr := fmt.Errorf("invalid http server address: %s", addr)
if !strings.Contains(addr, ":") {
return addrErr
}
parts := strings.Split(addr, ":")
if len(parts) != 2 {
return addrErr
}
port := parts[1]
if port == "" {
return addrErr
}
portInt, err := strconv.Atoi(port)
if err != nil {
return addrErr
}
if portInt < 1 || 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{}
if !c.disableRouteLogger && !noRouteLogger {
middleware = append(middleware, LoggerMiddlewareFn)
}
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...)
}
// setRouter sets the router's default handlers if they are not already set.
func (c *config) setRouter(_ context.Context) {
l := c.logger
middleware := c.commonMiddleware(false, 0)
if c.router.NotFound == nil {
c.router.NotFound = ApplyMiddleware(
MiddlewareArgs{
Path: "404",
Description: http.StatusText(http.StatusNotFound),
TraceIDHeaderName: c.traceIDHeaderName,
RedactFunc: c.redactFn,
Logger: l,
Rnd: c.rnd,
},
c.notFoundHandlerFunc,
middleware...,
)
}
if c.router.MethodNotAllowed == nil {
c.router.MethodNotAllowed = ApplyMiddleware(
MiddlewareArgs{
Path: "405",
Description: http.StatusText(http.StatusMethodNotAllowed),
TraceIDHeaderName: c.traceIDHeaderName,
RedactFunc: c.redactFn,
Logger: l,
Rnd: c.rnd,
},
c.methodNotAllowedHandlerFunc,
middleware...,
)
}
if c.router.PanicHandler == nil {
c.router.PanicHandler = func(w http.ResponseWriter, r *http.Request, p any) {
c.logger.With(
slog.Any("error", p),
slog.String("stacktrace", string(debug.Stack())),
).Error("panic")
ApplyMiddleware(
MiddlewareArgs{
Path: "500",
Description: http.StatusText(http.StatusInternalServerError),
TraceIDHeaderName: c.traceIDHeaderName,
RedactFunc: c.redactFn,
Logger: l,
Rnd: c.rnd,
},
c.panicHandlerFunc,
middleware...,
).ServeHTTP(w, r)
}
}
}
// defaultIndexHandler returns the default index handler.
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)
},
)
}