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
16 changes: 15 additions & 1 deletion middleware/compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,21 @@ 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) {
token := strings.TrimSpace(v)
// Strip quality parameter (e.g. "gzip;q=0.5" → "gzip")
if idx := strings.IndexByte(token, ';'); idx >= 0 {
params := strings.TrimSpace(token[idx+1:])
token = strings.TrimSpace(token[:idx])
// q=0 means not acceptable per RFC 9110 Section 12.5.3.
// Check exact "q=0" or "q=0.0" (not "q=0.5" or "q=0.1").
if len(params) >= 3 && strings.HasPrefix(params, "q=") {
qv := params[2:]
if qv == "0" || qv == "0.0" || qv == "0.00" || qv == "0.000" {
continue
}
}
}
if strings.EqualFold(token, encoding) {
return true
}
}
Expand Down
87 changes: 87 additions & 0 deletions middleware/compress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,90 @@ func decodeResponseBody(t *testing.T, resp *http.Response) string {

return string(respBody)
}


func TestMatchAcceptEncoding(t *testing.T) {
tests := []struct {
name string
accepted []string
encoding string
want bool
}{
{
name: "exact match",
accepted: []string{"gzip", "deflate"},
encoding: "gzip",
want: true,
},
{
name: "no match",
accepted: []string{"gzip", "deflate"},
encoding: "br",
want: false,
},
{
name: "substring false positive: br contains b",
accepted: []string{"br"},
encoding: "b",
want: false,
},
{
name: "substring false positive: bgzip contains gzip",
accepted: []string{"bgzip"},
encoding: "gzip",
want: false,
},
{
name: "q=0 means not acceptable",
accepted: []string{"gzip;q=0", "deflate"},
encoding: "gzip",
want: false,
},
{
name: "q=0 with spaces",
accepted: []string{" gzip; q=0 "},
encoding: "gzip",
want: false,
},
{
name: "q=1.0 is acceptable",
accepted: []string{"gzip;q=1.0"},
encoding: "gzip",
want: true,
},
{
name: "q=0.5 is acceptable",
accepted: []string{"gzip;q=0.5", "br;q=1.0"},
encoding: "gzip",
want: true,
},
{
name: "case insensitive",
accepted: []string{"GZIP"},
encoding: "gzip",
want: true,
},
{
name: "empty accepted list",
accepted: []string{},
encoding: "gzip",
want: false,
},
{
name: "q=0.0001 is acceptable (q=0 exact check)",
accepted: []string{"gzip;q=0.0001"},
encoding: "gzip",
want: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := matchAcceptEncoding(tt.accepted, tt.encoding)
if got != tt.want {
t.Errorf("matchAcceptEncoding(%v, %q) = %v, want %v",
tt.accepted, tt.encoding, got, tt.want)
}
})
}
}