Procházet zdrojové kódy

fix(response): add vary header for encoding negotiation

Set `Vary: Accept-Encoding` when large responses
are eligible for compression so caches keep encoded and
identity variants separate.
Frédéric Guillot před 2 týdny
rodič
revize
ab0ea2da43

+ 1 - 0
internal/http/response/builder.go

@@ -120,6 +120,7 @@ func (b *Builder) writeHeaders() {
 
 func (b *Builder) compress(data []byte) {
 	if b.enableCompression && len(data) > compressionThreshold {
+		b.headers["Vary"] = "Accept-Encoding"
 		acceptEncoding := b.r.Header.Get("Accept-Encoding")
 		switch {
 		case strings.Contains(acceptEncoding, "br"):

+ 24 - 0
internal/http/response/builder_test.go

@@ -277,6 +277,12 @@ func TestBuildResponseWithDeflateCompression(t *testing.T) {
 	if actual != expected {
 		t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
 	}
+
+	expectedVary := "Accept-Encoding"
+	actualVary := resp.Header.Get("Vary")
+	if actualVary != expectedVary {
+		t.Fatalf(`Unexpected vary header value, got %q instead of %q`, actualVary, expectedVary)
+	}
 }
 
 func TestBuildResponseWithCompressionDisabled(t *testing.T) {
@@ -301,6 +307,12 @@ func TestBuildResponseWithCompressionDisabled(t *testing.T) {
 	if actual != expected {
 		t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
 	}
+
+	expectedVary := ""
+	actualVary := resp.Header.Get("Vary")
+	if actualVary != expectedVary {
+		t.Fatalf(`Unexpected vary header value, got %q instead of %q`, actualVary, expectedVary)
+	}
 }
 
 func TestBuildResponseWithDeflateCompressionAndSmallPayload(t *testing.T) {
@@ -325,6 +337,12 @@ func TestBuildResponseWithDeflateCompressionAndSmallPayload(t *testing.T) {
 	if actual != expected {
 		t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
 	}
+
+	expectedVary := ""
+	actualVary := resp.Header.Get("Vary")
+	if actualVary != expectedVary {
+		t.Fatalf(`Unexpected vary header value, got %q instead of %q`, actualVary, expectedVary)
+	}
 }
 
 func TestBuildResponseWithoutCompressionHeader(t *testing.T) {
@@ -348,6 +366,12 @@ func TestBuildResponseWithoutCompressionHeader(t *testing.T) {
 	if actual != expected {
 		t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
 	}
+
+	expectedVary := "Accept-Encoding"
+	actualVary := resp.Header.Get("Vary")
+	if actualVary != expectedVary {
+		t.Fatalf(`Unexpected vary header value, got %q instead of %q`, actualVary, expectedVary)
+	}
 }
 
 func TestBuildResponseWithReaderBody(t *testing.T) {