Skip to content

Commit 17607ee

Browse files
committed
feat(acceptHeaders): avoid matching zero-quality item
See also: https://www.rfc-editor.org/rfc/rfc9110.html#quality.values > The weight is normalized to a real number in the range 0 through 1, ... > a value of 0 means "not acceptable".
1 parent 5f938f5 commit 17607ee

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

src/acceptHeaders/accepts.go

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ func (accepts Accepts) GetPreferredValue(availables []string) (index int, value
2828
}
2929
}
3030
}
31+
32+
index = -1
3133
return
3234
}
3335

@@ -38,9 +40,19 @@ func ParseAccepts(input string) Accepts {
3840
return nil
3941
}
4042

41-
accepts := make(Accepts, entryCount)
43+
accepts := make(Accepts, 0, entryCount)
4244
for i := 0; i < entryCount; i++ {
43-
accepts[i] = parseAcceptItem(strings.TrimSpace(entries[i]))
45+
input := strings.TrimSpace(entries[i])
46+
if len(input) == 0 {
47+
continue
48+
}
49+
50+
accept := parseAcceptItem(input)
51+
if accept.quality <= 0 {
52+
continue
53+
}
54+
55+
accepts = append(accepts, accept)
4456
}
4557
sort.Sort(accepts)
4658
return accepts

src/acceptHeaders/accepts_test.go

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,11 +127,12 @@ func TestParseAcceptEncoding(t *testing.T) {
127127
}
128128

129129
func TestParseAcceptEncoding2(t *testing.T) {
130-
acceptEncoding := "gzip;v=b3;q=0.9, deflate"
130+
acceptEncoding := "gzip;v=b3;q=0.9, deflate, br;q=0.0, zstd; q=0, "
131131
accepts := ParseAccepts(acceptEncoding)
132132

133133
var index int
134134
var preferred string
135+
var ok bool
135136
index, preferred, _ = accepts.GetPreferredValue([]string{"gzip"})
136137
if index != 0 {
137138
t.Error(index)
@@ -187,4 +188,23 @@ func TestParseAcceptEncoding2(t *testing.T) {
187188
if preferred != "deflate" {
188189
t.Error(preferred)
189190
}
191+
192+
index, preferred, ok = accepts.GetPreferredValue([]string{"zstd", "br"})
193+
if index != -1 {
194+
t.Error(index)
195+
}
196+
if ok {
197+
t.Error(preferred)
198+
}
199+
200+
index, preferred, ok = accepts.GetPreferredValue([]string{"zstd", "br", "gzip"})
201+
if index != 2 {
202+
t.Error(index)
203+
}
204+
if preferred != "gzip" {
205+
t.Error(preferred)
206+
}
207+
if !ok {
208+
t.Error(preferred)
209+
}
190210
}

0 commit comments

Comments
 (0)