-
Notifications
You must be signed in to change notification settings - Fork 11
/
headers.go
111 lines (98 loc) · 2.48 KB
/
headers.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package abstractions
import "strings"
type header struct {
headers map[string]map[string]struct{}
}
type void struct{}
var voidInstance void
func normalizeHeaderKey(key string) string {
return strings.ToLower(strings.Trim(key, " "))
}
//Add adds a new header or append a new value to an existing header
func (r *header) Add(key string, value string, additionalValues ...string) {
normalizedKey := normalizeHeaderKey(key)
if normalizedKey == "" || value == "" {
return
}
if r.headers == nil {
r.headers = make(map[string]map[string]struct{})
}
if r.headers[normalizedKey] == nil {
r.headers[normalizedKey] = make(map[string]struct{})
}
r.headers[normalizedKey][value] = voidInstance
for _, v := range additionalValues {
r.headers[normalizedKey][v] = voidInstance
}
}
//Get returns the values for the specific header
func (r *header) Get(key string) []string {
if r.headers == nil {
return nil
}
normalizedKey := normalizeHeaderKey(key)
if r.headers[normalizedKey] == nil {
return make([]string, 0)
}
values := make([]string, 0, len(r.headers[normalizedKey]))
for k := range r.headers[normalizedKey] {
values = append(values, k)
}
return values
}
//Remove removes the specific header and all its values
func (r *header) Remove(key string) {
if r.headers == nil {
return
}
normalizedKey := normalizeHeaderKey(key)
delete(r.headers, normalizedKey)
}
//RemoveValue remove the value for the specific header
func (r *header) RemoveValue(key string, value string) {
if r.headers == nil {
return
}
normalizedKey := normalizeHeaderKey(key)
if r.headers[normalizedKey] == nil {
return
}
delete(r.headers[normalizedKey], value)
if len(r.headers[normalizedKey]) == 0 {
delete(r.headers, normalizedKey)
}
}
//ContainsKey check if the key exists in the headers
func (r *header) ContainsKey(key string) bool {
if r.headers == nil {
return false
}
normalizedKey := normalizeHeaderKey(key)
return r.headers[normalizedKey] != nil
}
//Clear clear all headers
func (r *header) Clear() {
r.headers = nil
}
//AddAll adds all headers from the other headers
func (r *header) AddAll(other *header) {
if other == nil || other.headers == nil {
return
}
for k, v := range other.headers {
for k2 := range v {
r.Add(k, k2)
}
}
}
//ListKeys returns all the keys in the headers
func (r *header) ListKeys() []string {
if r.headers == nil {
return make([]string, 0)
}
keys := make([]string, 0, len(r.headers))
for k := range r.headers {
keys = append(keys, k)
}
return keys
}