From 5e2b7325abdfae769918297dc42f0b7e2de10b19 Mon Sep 17 00:00:00 2001 From: Roman Dmytrenko Date: Wed, 29 Jan 2025 00:15:35 +0200 Subject: [PATCH] fix: apply UI additional http headers only for requests to UI assets (#3853) The additional UI http headers are added to each api requests. They add extra bytes to each api call without any value (up to 15-20% of request size). This work rearrange the code to apply those headers only for requests to UI assets. --- internal/cmd/http.go | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/internal/cmd/http.go b/internal/cmd/http.go index 50db311d8..545ca2338 100644 --- a/internal/cmd/http.go +++ b/internal/cmd/http.go @@ -111,12 +111,6 @@ func NewHTTPServer( logger.Debug("CORS enabled", zap.Strings("allowed_origins", cfg.Cors.AllowedOrigins)) } - // set additional headers enabling the UI to be served securely - // ie: Content-Security-Policy, X-Content-Type-Options, etc. - for k, v := range ui.AdditionalHeaders() { - r.Use(middleware.SetHeader(k, v)) - } - r.Use(middleware.RequestID) r.Use(middleware.RealIP) r.Use(func(h http.Handler) http.Handler { @@ -209,7 +203,16 @@ func NewHTTPServer( return nil, fmt.Errorf("mounting ui: %w", err) } - r.Mount("/", http.FileServer(http.FS(fs))) + r.With(func(next http.Handler) http.Handler { + // set additional headers enabling the UI to be served securely + // ie: Content-Security-Policy, X-Content-Type-Options, etc. + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + for k, v := range ui.AdditionalHeaders() { + w.Header().Set(k, v) + } + next.ServeHTTP(w, r) + }) + }).Mount("/", http.FileServer(http.FS(fs))) server.Server = &http.Server{ Addr: fmt.Sprintf("%s:%d", cfg.Server.Host, httpPort),