This repository has been archived by the owner on Dec 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrfc7240.go
96 lines (89 loc) · 2.41 KB
/
rfc7240.go
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
package httpheader
import (
"net/http"
"strings"
)
// A Pref contains a preference's value and any associated parameters (RFC 7240).
type Pref struct {
Value string
Params map[string]string
}
// Prefer parses the Prefer header from h (RFC 7240), returning a map where keys
// are preference names.
func Prefer(h http.Header) map[string]Pref {
values := h["Prefer"]
if values == nil {
return nil
}
r := make(map[string]Pref)
for v, vs := iterElems("", values); v != ""; v, vs = iterElems(v, vs) {
var name string
var pref Pref
name, pref.Value, v = consumeParam(v)
pref.Params, v = consumeParams(v)
// RFC 7240 page 5: ``If any preference is specified more than once,
// only the first instance is to be considered.''
if _, seen := r[name]; seen {
continue
}
pref.Value = canonicalPref(name, pref.Value)
r[name] = pref
}
return r
}
// SetPrefer replaces the Prefer header in h (RFC 7240).
func SetPrefer(h http.Header, prefs map[string]Pref) {
if len(prefs) == 0 {
h.Del("Prefer")
return
}
b := &strings.Builder{}
var wrote bool
for name, pref := range prefs {
wrote = writeDirective(b, wrote, name, pref.Value)
writeNullableParams(b, pref.Params)
}
h.Set("Prefer", b.String())
}
// PreferenceApplied parses the Preference-Applied header from h
// (RFC 7240 Section 3), returning a map where keys are preference names.
func PreferenceApplied(h http.Header) map[string]string {
values := h["Preference-Applied"]
if values == nil {
return nil
}
r := make(map[string]string)
for v, vs := iterElems("", values); v != ""; v, vs = iterElems(v, vs) {
var name, value string
name, value, v = consumeParam(v)
if _, seen := r[name]; seen {
continue
}
value = canonicalPref(name, value)
r[name] = value
}
return r
}
// SetPreferenceApplied replaces the Preference-Applied header in h
// (RFC 7240 Section 3).
func SetPreferenceApplied(h http.Header, prefs map[string]string) {
if len(prefs) == 0 {
h.Del("Preference-Applied")
return
}
b := &strings.Builder{}
var wrote bool
for name, value := range prefs {
wrote = writeDirective(b, wrote, name, value)
}
h.Set("Preference-Applied", b.String())
}
func canonicalPref(name, value string) string {
switch name {
case "handling", "return":
// These preferences are case-insensitive because RFC 7240 defines them
// with ABNF's case-insensitive literal strings (RFC 5234 Section 2.3).
value = strings.ToLower(value)
}
return value
}