From 70a97c0db869ce0de71e6aac0903ae4933984843 Mon Sep 17 00:00:00 2001 From: Gregor Krmelj Date: Thu, 19 Sep 2019 00:48:37 +0200 Subject: [PATCH] Add cache-control HTTP header to badge response (#2328) Since we serve the badge as an image using HTTP GET, cache systems (incl. GitHub's CDN - Fastly) like to cache the image thus the badge becomes stale rendering it useless. Adding the appropriate Cache-Control HTTP header we direct cache systems and web browsers not to cache the contents of the response. --- server/badge/badge.go | 3 +++ server/badge/badge_test.go | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/server/badge/badge.go b/server/badge/badge.go index 9b2cf122a7..fd61af11aa 100644 --- a/server/badge/badge.go +++ b/server/badge/badge.go @@ -121,6 +121,9 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { badge = replaceFirstGroupSubMatch(rightText1Pattern, badge, rightText) badge = replaceFirstGroupSubMatch(rightText2Pattern, badge, rightText) w.Header().Set("Content-Type", "image/svg+xml") + + //Ask cache's to not cache the contents in order prevent the badge from becoming stale + w.Header().Set("Cache-Control", "private, no-store") w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(badge)) } diff --git a/server/badge/badge_test.go b/server/badge/badge_test.go index b84acbf2bb..04e10858dd 100644 --- a/server/badge/badge_test.go +++ b/server/badge/badge_test.go @@ -54,6 +54,8 @@ func TestHandlerFeatureIsEnabled(t *testing.T) { rr := httptest.NewRecorder() handler.ServeHTTP(rr, req) + assert.Equal(t, "private, no-store", rr.Header().Get("Cache-Control")) + response := rr.Body.String() assert.Equal(t, success, leftPathColorPattern.FindStringSubmatch(response)[1]) assert.Equal(t, success, rightPathColorPattern.FindStringSubmatch(response)[1]) @@ -74,6 +76,8 @@ func TestHandlerFeatureIsDisabled(t *testing.T) { rr := httptest.NewRecorder() handler.ServeHTTP(rr, req) + assert.Equal(t, "private, no-store", rr.Header().Get("Cache-Control")) + response := rr.Body.String() assert.Equal(t, unknown, leftPathColorPattern.FindStringSubmatch(response)[1]) assert.Equal(t, unknown, rightPathColorPattern.FindStringSubmatch(response)[1])