HTTPMiddleware builds a http middleware that: - Adds contexted request logger with {method,path,ip} into request.Context - Collects _http_duration_seconds metrics with {path,method} dimensions, if latencyMetricsName is specified - Wraps handler with http.TimeoutHandler with `h
(ctx context.Context, opts ...HTTPMiddlewareOption)
| 344 | // - Collects <latencyMetricsName>_http_duration_seconds metrics with |
| 345 | // {path,method} dimensions, if latencyMetricsName is specified |
| 346 | // |
| 347 | // - Wraps handler with http.TimeoutHandler with `handlerTimeout`. |
| 348 | // |
| 349 | // - Wraps request.Body with MaxBytesReader with `requestBodyLimit`. |
| 350 | // |
| 351 | // - Instruments OpenTelemetry by adding a span to the request context |
| 352 | // that tracks the response and its return codes |
| 353 | func NewHTTPMiddleware(ctx context.Context, opts ...HTTPMiddlewareOption) []mux.MiddlewareFunc { |
| 354 | m := &httpMiddleware{ |
| 355 | handlerTimeout: 5 * time.Second, |
| 356 | requestBodyLimit: int64(1 << 20), // 1 MB |
| 357 | prometheusRegisterer: prometheus.DefaultRegisterer, |
| 358 | telemetryExcludedRoutes: map[string]interface{}{ |
| 359 | // Exclude /healthz |
| 360 | httpHealthRoutePath: nil, |
| 361 | }, |
| 362 | } |
| 363 | |
| 364 | // Apply options |
| 365 | for _, o := range opts { |
| 366 | o(m) |
| 367 | } |
| 368 | |
| 369 | var mw []mux.MiddlewareFunc |
| 370 | |
| 371 | // Add telemetry middleware if enabled |
| 372 | if m.telemetryServiceName != "" { |
| 373 | mw = append(mw, telemetryMiddleware(m.telemetryServiceName, m.telemetryExcludedRoutes)) |
| 374 | if len(m.telemetryAttributes) > 0 { |
| 375 | mw = append(mw, telemetryAttributesMiddleware(m.telemetryAttributes)) |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | mw = append(mw, loggingMiddleware(ctx), metricsMiddleware(m.latencyMetricsName, m.prometheusRegisterer)) |
| 380 | |
| 381 | // Add timeout middleware |
| 382 | if m.handlerTimeout > 0 { |
| 383 | mw = append(mw, timeoutMiddleware(m.handlerTimeout)) |
| 384 | } |
| 385 | |
| 386 | // Add max request body middleware |
| 387 | if m.requestBodyLimit > 0 { |
| 388 | mw = append(mw, maxRequestBodyMiddleware(m.requestBodyLimit)) |