fix(cache): rely on if-modified-since header to serve static files (#7372)

This commit is contained in:
Vibhu Pandey 2025-03-20 01:09:52 +05:30 committed by GitHub
parent 3d3dd98549
commit 95b94a9da7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 12 additions and 8 deletions

View File

@ -3,6 +3,7 @@ package middleware
import (
"net/http"
"strconv"
"strings"
"time"
)
@ -11,18 +12,21 @@ type Cache struct {
}
func NewCache(maxAge time.Duration) *Cache {
if maxAge == 0 {
maxAge = 7 * 24 * time.Hour
}
return &Cache{
maxAge: maxAge,
}
}
func (middleware *Cache) Wrap(next http.Handler) http.Handler {
// Cache-Control: no-cache is equivalent to Cache-Control: max-age=0, must-revalidate as most HTTP/1.0 caches don't support no-cache directives
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Cache-Control", "max-age="+strconv.Itoa(int(middleware.maxAge.Seconds())))
directives := []string{
"max-age=" + strconv.Itoa(int(middleware.maxAge.Seconds())),
"no-cache", // Note that no-cache does not mean "don't cache". no-cache allows caches to store a response but requires them to revalidate it before reuse.
"private", //If you forget to add private to a response with personalized content, then that response can be stored in a shared cache and end up being reused for multiple users, which can cause personal information to leak.
"must-revalidate", // HTTP allows caches to reuse stale responses when they are disconnected from the origin server. must-revalidate is a way to prevent this from happening - either the stored response is revalidated with the origin server or a 504 (Gateway Timeout) response is generated.
}
rw.Header().Set("Cache-Control", strings.Join(directives, ","))
next.ServeHTTP(rw, req)
})
}

View File

@ -7,6 +7,7 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@ -50,7 +51,7 @@ func TestCache(t *testing.T) {
actual := res.Header.Get("Cache-control")
require.NoError(t, err)
require.Equal(t, "max-age="+strconv.Itoa(int(age.Seconds())), string(actual))
assert.Contains(t, actual, "max-age="+strconv.Itoa(int(age.Seconds())))
})
}
}

View File

@ -6,7 +6,6 @@ import (
"net/http"
"os"
"path/filepath"
"time"
"github.com/gorilla/mux"
"go.signoz.io/signoz/pkg/factory"
@ -52,7 +51,7 @@ func New(ctx context.Context, settings factory.ProviderSettings, config web.Conf
}
func (provider *provider) AddToRouter(router *mux.Router) error {
cache := middleware.NewCache(7 * 24 * time.Hour)
cache := middleware.NewCache(0)
err := router.PathPrefix(provider.config.Prefix).
Handler(
http.StripPrefix(