aboutsummaryrefslogtreecommitdiff
path: root/net/http/accept.go
blob: cabfc4873a00fef614c487c3fcb2b511ba8284a9 (plain)
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package http

import (
	"fmt"
	"mime"
	"reflect"
	"regexp"
	"sort"
	"strconv"
	"strings"
)

type MediaType struct {
	Type       string
	Subtype    string
	Parameters map[string]string
	Weight     float64
	originalQ  string
}

func ParseMediaType(v string) (*MediaType, error) {
	mt, params, err := mime.ParseMediaType(v)
	if err != nil {
		return nil, err
	}

	majorMinor := strings.Split(mt, "/")
	if len(majorMinor) != 2 {
		return nil, fmt.Errorf("Invalid major/minor media type: %s", mt)
	}

	// No q should be weight 1.0, per spec
	q := float64(1)
	sq, ok := params["q"]
	if ok {
		delete(params, "q")
		q, err = parseQ(sq)
		if err != nil {
			return nil, err
		}
	}

	return &MediaType{
		Type:       majorMinor[0],
		Subtype:    majorMinor[1],
		Parameters: params,
		Weight:     q,
		originalQ:  sq,
	}, nil
}

func (m MediaType) String() string {
	b := strings.Builder{}
	b.WriteString(m.Type + "/" + m.Subtype)

	params := []string{}
	for k, v := range m.Parameters {
		params = append(params, fmt.Sprintf("%s=%s", k, v))
	}

	// Keep them in the same order so they're comparable
	sort.Strings(params)

	// Q should always be last per RFC9110
	if m.originalQ != "" {
		params = append(params, fmt.Sprintf("q=%s", m.originalQ))
	}

	if len(params) > 0 {
		b.WriteString(";")
		b.WriteString(strings.Join(params, ";"))
	}

	return b.String()
}

func (m MediaType) Specificity() int {
	s := 0

	if m.Type != "*" {
		s += 1
	}
	if m.Subtype != "*" {
		s += 1
	}
	if m.Parameters != nil {
		s += len(m.Parameters)
	}

	return s
}

func (m MediaType) Satisfies(v MediaType) bool {
	if m.Equal(v) {
		return true
	}

	if m.Type != v.Type && m.Type != "*" && v.Type != "*" {
		return false
	}

	if m.Subtype != v.Subtype && m.Subtype != "*" && v.Subtype != "*" {
		return false
	}

	return reflect.DeepEqual(m.Parameters, v.Parameters)
}

func (m MediaType) Equal(v MediaType) bool {
	return m.Type == v.Type &&
		m.Subtype == v.Subtype &&
		reflect.DeepEqual(m.Parameters, v.Parameters)
}

type AcceptableTypes []*MediaType

func (a AcceptableTypes) Sorted() AcceptableTypes { sort.Stable(sort.Reverse(a)); return a }
func (a AcceptableTypes) Len() int                { return len(a) }
func (a AcceptableTypes) Less(i, j int) bool      { return a[i].Weight < a[j].Weight }
func (a AcceptableTypes) Swap(i, j int)           { a[i], a[j] = a[j], a[i] }

// FindMatch returns the MediaType in the set that has the best match
// for the passed media types as well as the media type that determined
// the match. According to the rules of RFC7231, the most specific match
// wins in order of weight. This function assumes that both values are
// sorted.
func (a AcceptableTypes) FindMatch(values AcceptableTypes) (match *MediaType, matcher *MediaType) {
	if len(a) == 0 || len(values) == 0 {
		return nil, nil
	}

	candidates := AcceptableTypes{}

	// Return the highest precedence match for the type. If there is no
	// exact match then the most specific match with the highest precedence
	// should win.
	for _, matcher = range values {
		for _, match = range a {
			if match.Equal(*matcher) {
				return match, matcher
			}

			if match.Satisfies(*matcher) {
				candidates = append(candidates, match)
			}
		}

		if len(candidates) != 0 {
			break
		}
	}

	if len(candidates) == 0 {
		return nil, nil
	}

	// Sort ascending by specificity
	sort.SliceStable(candidates, func(i, j int) bool {
		return candidates[i].Specificity() < candidates[j].Specificity()
	})

	return candidates[len(candidates)-1], matcher
}

// ParseAccept parses a set of Accept headers and scores them per the
// rules in RFC7231, returning a slice of headers in descending order of
// priority. If the Accept header occurs multiple times in the request
// the result of all headers will be combined and scored together as if
// they were all in one header line.
//
// See: https://tools.ietf.org/html/rfc7231#section-5.3.2
func ParseAccept(values []string) (AcceptableTypes, error) {
	all := AcceptableTypes{}

	for _, l := range values {
		t, err := parseAcceptLine(l)
		if err != nil {
			return nil, err
		}
		all = append(all, t...)
	}

	return all.Sorted(), nil
}

func parseAcceptLine(l string) (AcceptableTypes, error) {
	out := AcceptableTypes{}

	for _, t := range strings.Split(l, ",") {
		mt, err := ParseMediaType(t)
		if err != nil {
			return nil, err
		}
		out = append(out, mt)
	}

	return out, nil
}

// https://tools.ietf.org/html/rfc7231#section-5.3.1
var validateQ = regexp.MustCompile(`(0\.[0-9]{1,3}|1\.0{1,3})$`)

func parseQ(v string) (float64, error) {
	if !validateQ.Match([]byte(v)) {
		return 0.0, fmt.Errorf("Invalid format for Q")
	}

	f, err := strconv.ParseFloat(v, 64)
	if err != nil {
		return 0.0, err
	}

	return f, nil
}