From 2aaf37b7667da0f41fef0c61ff5454d295e6f09c Mon Sep 17 00:00:00 2001 From: Sergey Stepanov Date: Sun, 17 Mar 2024 16:35:58 +0300 Subject: [PATCH] Add Cache-Control for serving static files Static files will be rechecked every 3 days instead of unlimited cache time. The Cache-Control header is mandatory in order to make browsers handle cache properly with Go's FileServer. The option can be modified in the server.CacheControl line of the config file. --- pkg/config/config.yaml | 1 + pkg/config/shared.go | 7 ++++--- pkg/coordinator/coordinator.go | 6 ++++++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/pkg/config/config.yaml b/pkg/config/config.yaml index 39b695ea..57cb39de 100644 --- a/pkg/config/config.yaml +++ b/pkg/config/config.yaml @@ -59,6 +59,7 @@ coordinator: # HTTP(S) server config server: address: :8000 + cacheControl: "max-age=259200, must-revalidate" https: false # Letsencrypt or self cert config tls: diff --git a/pkg/config/shared.go b/pkg/config/shared.go index 026b79d3..ae99d289 100644 --- a/pkg/config/shared.go +++ b/pkg/config/shared.go @@ -30,9 +30,10 @@ type Monitoring struct { func (c *Monitoring) IsEnabled() bool { return c.MetricEnabled || c.ProfilingEnabled } type Server struct { - Address string - Https bool - Tls struct { + Address string + CacheControl string + Https bool + Tls struct { Address string Domain string HttpsKey string diff --git a/pkg/coordinator/coordinator.go b/pkg/coordinator/coordinator.go index bdb21067..cb80b739 100644 --- a/pkg/coordinator/coordinator.go +++ b/pkg/coordinator/coordinator.go @@ -92,6 +92,9 @@ func index(conf config.CoordinatorConfig, log *logger.Logger) httpx.Handler { if conf.Coordinator.Debug { log.Info().Msgf("Using auto-reloading index.html") return httpx.HandlerFunc(func(w httpx.ResponseWriter, r *httpx.Request) { + if conf.Coordinator.Server.CacheControl != "" { + w.Header().Add("Cache-Control", conf.Coordinator.Server.CacheControl) + } if r.URL.Path == "/" || strings.HasSuffix(r.URL.Path, "/index.html") { tpl := template.Must(template.ParseFiles(indexHTML)) handler(tpl, w, r) @@ -102,6 +105,9 @@ func index(conf config.CoordinatorConfig, log *logger.Logger) httpx.Handler { } return httpx.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if conf.Coordinator.Server.CacheControl != "" { + w.Header().Add("Cache-Control", conf.Coordinator.Server.CacheControl) + } if r.URL.Path == "/" || strings.HasSuffix(r.URL.Path, "/index.html") { handler(indexTpl, w, r) return