forked from ProtonMail/go-proton-api
-
Notifications
You must be signed in to change notification settings - Fork 4
/
header_types.go
109 lines (83 loc) · 1.86 KB
/
header_types.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
package proton
import (
"encoding/json"
"errors"
"gitlab.com/c0b/go-ordered-json"
)
var ErrBadHeader = errors.New("bad header")
type Headers struct {
Values map[string][]string
Order []string
}
func (h *Headers) UnmarshalJSON(b []byte) error {
type rawHeaders map[string]any
raw := make(rawHeaders)
// Need to use a different type to deserialize, because there still is no official way for json to decode an object
// with the fields in order https://github.com/golang/go/issues/27179.
orderedMap := ordered.NewOrderedMap()
if err := orderedMap.UnmarshalJSON(b); err != nil {
return err
}
header := Headers{
Values: make(map[string][]string, len(raw)),
Order: make([]string, 0, len(raw)),
}
iter := orderedMap.EntriesIter()
for {
entry, ok := iter()
if !ok {
break
}
switch val := entry.Value.(type) {
case string:
header.Values[entry.Key] = []string{val}
case []any:
for _, val := range val {
switch val := val.(type) {
case string:
header.Values[entry.Key] = append(header.Values[entry.Key], val)
default:
return ErrBadHeader
}
}
default:
return ErrBadHeader
}
header.Order = append(header.Order, entry.Key)
}
*h = header
return nil
}
func (h Headers) MarshalJSON() ([]byte, error) {
// Manually Serialize to preserve oder
if len(h.Values) == 0 {
return []byte{'{', '}'}, nil
}
out := make([]byte, 0, 64)
out = append(out, '{')
for _, k := range h.Order {
v := h.Values[k]
if len(v) == 0 {
continue
}
key, err := json.Marshal(k)
if err != nil {
return nil, err
}
var val []byte
if len(v) == 1 {
val, err = json.Marshal(v[0])
} else {
val, err = json.Marshal(v)
}
if err != nil {
return nil, err
}
out = append(out, key...)
out = append(out, ':')
out = append(out, val...)
out = append(out, ',')
}
out[len(out)-1] = '}'
return out, nil
}