Skip to content

Commit

Permalink
Add Cache-Control: no-store (#156)
Browse files Browse the repository at this point in the history
I want to proxy this service behind Cloudflare in order to hide its IP.
Cloudflare has its own rules for what to cache and how long. I don't
want to rely on that, this force it to never cache.
  • Loading branch information
getkey authored Oct 31, 2024
1 parent 6b1828e commit 42c9c5b
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
4 changes: 3 additions & 1 deletion cmd/signaling/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ func main() {
mux, cleanup := internal.Signaling(ctx, store, credentialsClient)

cors := cors.Default()
handler := logging.Middleware(cors.Handler(mux), logger)
handler := cors.Handler(mux)
handler = util.NoStoreMiddleware(handler)
handler = logging.Middleware(handler, logger)

if metricsURL, ok := os.LookupEnv("METRICS_URL"); ok {
client := metrics.NewClient(metricsURL)
Expand Down
9 changes: 9 additions & 0 deletions internal/util/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,12 @@ func ShouldIgnoreNetworkError(err error) bool {
}
return false
}

func NoStoreMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
w.Header().Set("Cache-Control", "no-store")
}
next.ServeHTTP(w, r)
})
}
39 changes: 39 additions & 0 deletions internal/util/http_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package util

import (
"net/http"
"net/http/httptest"
"testing"
)

func TestNoStoreMiddleware(t *testing.T) {
sampleHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})

handler := NoStoreMiddleware(sampleHandler)

tests := []struct {
method string
expectedCacheControl string
}{
{"GET", "no-store"},
{"POST", ""},
}

for _, tt := range tests {
req, err := http.NewRequest(tt.method, "/test", nil)
if err != nil {
t.Fatalf("Could not create %v request: %v", tt.method, err)
}

recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)

actualCacheControl := recorder.Header().Get("Cache-Control")
if actualCacheControl != tt.expectedCacheControl {
t.Errorf("expected Cache-Control header to be %q for %v request, got %q",
tt.expectedCacheControl, tt.method, actualCacheControl)
}
}
}

0 comments on commit 42c9c5b

Please sign in to comment.