1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
// SPDX-FileCopyrightText: 2026 Stefan Majewsky <majewsky@gmx.net>
// SPDX-License-Identifier: Apache-2.0
package accept_test
import (
"testing"
"go.xyrillian.de/gg/assert"
"go.xyrillian.de/gg/internal/accept"
. "go.xyrillian.de/gg/option"
)
func TestAcceptWithHeader(t *testing.T) {
h := accept.ParseHeader([]string{"text/*;q=0.3, text/plain;format=flowed, text/plain;format=fixed;q=0.4, */*;q=0.5"})
assert.Equal(t, h.Negotiate(
"image/png", // matches with q=0.5
"text/plain; format=fixed", // matches with q=0.4
), Some("image/png"))
assert.Equal(t, h.Negotiate(
"image/png", // matches with q=0.5
"text/plain; format=flowed", // matches with q=1.0
), Some("text/plain; format=flowed"))
assert.Equal(t, h.Negotiate(
"text/plain", // matches with q=0.7
"text/plain; format=flowed", // matches with q=1.0
), Some("text/plain; format=flowed"))
assert.Equal(t, h.Negotiate(
"text/plain", // matches with q=0.7
"text/plain; format=other", // matches with q=0.3
), Some("text/plain"))
assert.Equal(t, h.Negotiate(
"text/markdown", // matches with q=0.3
"text/plain", // matches with q=0.3 (but first wins)
), Some("text/markdown"))
}
func TestAcceptWithoutHeader(t *testing.T) {
// Negotiate() will always pick the first option
h := accept.ParseHeader(nil)
assert.Equal(t, h.Negotiate(
"image/png",
"image/jpeg",
), Some("image/png"))
assert.Equal(t, h.Negotiate(nil...), None[string]())
// malformed media types are ignored
assert.Equal(t, h.Negotiate(
"image/png/foo",
"image/jpeg",
), Some("image/jpeg"))
assert.Equal(t, h.Negotiate(
"image/png/foo",
"image/jpeg/foo",
), None[string]())
}
func TestAcceptWithMalformedHeader(t *testing.T) {
for _, brokenHeader := range []string{
"text/plain, text/markdown/foo", // malformed media type
"text/plain, image/png; q=high", // malformed q-value
"text/plain, image/jpeg; q=1.25", // q-value out of range
} {
h := accept.ParseHeader([]string{brokenHeader})
// broken headers are ignored completely, so the first option wins by default
assert.Equal(t, h.Negotiate(
"image/png",
"image/jpeg",
"text/plain",
), Some("image/png"))
}
}
|