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.
This commit is contained in:
Sergey Stepanov 2024-03-17 16:35:58 +03:00 committed by sergystepanov
parent 47bd72e1cd
commit 2aaf37b766
3 changed files with 11 additions and 3 deletions

View file

@ -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:

View file

@ -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

View file

@ -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