Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions middleware/compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,9 +239,25 @@ func (c *Compressor) selectEncoder(h http.Header, w io.Writer) (io.Writer, strin

func matchAcceptEncoding(accepted []string, encoding string) bool {
for _, v := range accepted {
if strings.Contains(v, encoding) {
return true
// Split on ";" to separate the encoding name from quality params (e.g. "gzip;q=0.5")
parts := strings.SplitN(strings.TrimSpace(v), ";", 2)
name := strings.TrimSpace(parts[0])

if name != encoding {
continue
}

// Per RFC 9110 §12.5.3, q=0 means the encoding is explicitly not acceptable
if len(parts) > 1 {
for _, param := range strings.Split(parts[1], ";") {
param = strings.TrimSpace(param)
if strings.EqualFold(param, "q=0") {
return false
}
}
}

return true
}
return false
}
Expand Down
35 changes: 35 additions & 0 deletions middleware/compress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,38 @@ func decodeResponseBody(t *testing.T, resp *http.Response) string {

return string(respBody)
}

func TestMatchAcceptEncoding(t *testing.T) {
tests := []struct {
accepted []string
encoding string
want bool
}{
// exact match
{[]string{"gzip"}, "gzip", true},
// q=0 means explicitly not acceptable
{[]string{"gzip;q=0"}, "gzip", false},
{[]string{"gzip; q=0"}, "gzip", false},
// q>0 is acceptable
{[]string{"gzip;q=0.5"}, "gzip", true},
{[]string{"gzip;q=1"}, "gzip", true},
// substring must not match (br != b)
{[]string{"br"}, "b", false},
// substring must not match (bgzip != gzip)
{[]string{"bgzip"}, "gzip", false},
// wildcard
{[]string{"*"}, "gzip", true},
// no match
{[]string{"deflate"}, "gzip", false},
// multiple encodings
{[]string{"deflate", "gzip"}, "gzip", true},
{[]string{"deflate", "gzip;q=0"}, "gzip", false},
}

for _, tc := range tests {
got := matchAcceptEncoding(tc.accepted, tc.encoding)
if got != tc.want {
t.Errorf("matchAcceptEncoding(%v, %q) = %v, want %v", tc.accepted, tc.encoding, got, tc.want)
}
}
}