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
18 changes: 16 additions & 2 deletions middleware/compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io"
"net"
"net/http"
"strconv"
"strings"
"sync"
)
Expand Down Expand Up @@ -239,9 +240,22 @@ 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
parts := strings.Split(v, ";")
if !strings.EqualFold(strings.TrimSpace(parts[0]), encoding) {
continue
}

for _, part := range parts[1:] {
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
if !ok || !strings.EqualFold(strings.TrimSpace(key), "q") {
continue
}
quality, err := strconv.ParseFloat(strings.TrimSpace(value), 64)
if err == nil && quality <= 0 {
return false
}
}
return true
}
return false
}
Expand Down
48 changes: 48 additions & 0 deletions middleware/compress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,54 @@ func TestCompressorWildcards(t *testing.T) {
}
}

func TestMatchAcceptEncoding(t *testing.T) {
tests := []struct {
name string
accepted []string
encoding string
want bool
}{
{
name: "matches exact encoding",
accepted: []string{"gzip"},
encoding: "gzip",
want: true,
},
{
name: "matches exact encoding with quality",
accepted: []string{"gzip;q=0.5"},
encoding: "gzip",
want: true,
},
{
name: "rejects exact encoding with zero quality",
accepted: []string{"gzip;q=0"},
encoding: "gzip",
want: false,
},
{
name: "rejects substring prefix match",
accepted: []string{"br"},
encoding: "b",
want: false,
},
{
name: "rejects substring suffix match",
accepted: []string{"bgzip"},
encoding: "gzip",
want: false,
},
}

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

func testRequestWithAcceptedEncodings(t *testing.T, ts *httptest.Server, method, path string, encodings ...string) (*http.Response, string) {
req, err := http.NewRequest(method, ts.URL+path, nil)
if err != nil {
Expand Down