-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_header.go
More file actions
85 lines (69 loc) · 1.86 KB
/
Copy pathhttp_header.go
File metadata and controls
85 lines (69 loc) · 1.86 KB
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
package jsonutil
import (
"encoding/json/jsontext"
"fmt"
"maps"
"net/http"
"net/textproto"
"slices"
)
// HTTPHeaderMarshal is a custom marshaler for http.Header, marshaling values as a single strings.
// It also marshals the keys in their canonical form.
// Note that we omit keys that don't have a value.
func HTTPHeaderMarshal(enc *jsontext.Encoder, m http.Header) error {
if m == nil {
return enc.WriteToken(jsontext.Null)
}
if err := enc.WriteToken(jsontext.BeginObject); err != nil {
return err
}
for _, key := range slices.Sorted(maps.Keys(m)) {
v := m[key]
if len(v) == 0 || v[0] == "" {
continue
}
if err := enc.WriteToken(jsontext.String(textproto.CanonicalMIMEHeaderKey(key))); err != nil {
return err
}
if err := enc.WriteToken(jsontext.String(v[0])); err != nil {
return err
}
}
return enc.WriteToken(jsontext.EndObject)
}
// HTTPHeaderUnmarshal is a custom unmarshaler for http.Header, unmarshaling values as single strings.
func HTTPHeaderUnmarshal(dec *jsontext.Decoder, h *http.Header) error {
tkn, err := dec.ReadToken()
if err != nil {
return err
}
switch tkn.Kind() {
case jsontext.KindBeginObject: // expected, continue below
*h = http.Header{}
case jsontext.KindNull:
*h = nil
return nil // nil map
default:
return fmt.Errorf("expected begin object, got %s", tkn.Kind())
}
for dec.PeekKind() != jsontext.KindEndObject {
keyTkn, err := dec.ReadToken()
if err != nil {
return err
}
if keyTkn.Kind() != jsontext.KindString {
return fmt.Errorf("expected string key, got %s", keyTkn.Kind())
}
key := keyTkn.String()
val, err := dec.ReadToken()
if err != nil {
return err
}
if val.Kind() != jsontext.KindString {
return fmt.Errorf("expected string value, got %s", val.Kind())
}
h.Set(key, val.String())
}
_, err = dec.ReadToken() // consume jsontext.KindEndObject
return err
}