From 02a435b6f1f315f040e1b686e33d36f861c72eb0 Mon Sep 17 00:00:00 2001 From: wjrjerome Date: Tue, 3 Sep 2024 16:19:41 +1000 Subject: [PATCH] fix: metrics server endpoint to have timeout --- internal/observability/metrics/metrics.go | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/internal/observability/metrics/metrics.go b/internal/observability/metrics/metrics.go index e6b07df..962bff1 100644 --- a/internal/observability/metrics/metrics.go +++ b/internal/observability/metrics/metrics.go @@ -17,8 +17,10 @@ import ( type Outcome string const ( - Success Outcome = "success" - Error Outcome = "error" + Success Outcome = "success" + Error Outcome = "error" + MetricRequestTimeout time.Duration = 5 * time.Second + MetricRequestIdleTimeout time.Duration = 10 * time.Second ) func (O Outcome) String() string { @@ -47,12 +49,21 @@ func initMetricsRouter(metricsPort int) { metricsRouter.Get("/metrics", func(w http.ResponseWriter, r *http.Request) { promhttp.Handler().ServeHTTP(w, r) }) + // Create a custom server with timeout settings + metricsAddr := fmt.Sprintf(":%d", metricsPort) + server := &http.Server{ + Addr: metricsAddr, + Handler: metricsRouter, + ReadTimeout: MetricRequestTimeout, + WriteTimeout: MetricRequestTimeout, + IdleTimeout: MetricRequestIdleTimeout, + } + // Start the server in a separate goroutine go func() { - metricsAddr := fmt.Sprintf(":%d", metricsPort) - err := http.ListenAndServe(metricsAddr, metricsRouter) - if err != nil { - log.Fatal().Err(err).Msgf("error starting metrics server on %s", metricsAddr) + log.Printf("Starting metrics server on %s", metricsAddr) + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatal().Err(err).Msgf("Error starting metrics server on %s", metricsAddr) } }() }