Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions http_header.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ func HTTPHeaderMarshal(enc *jsontext.Encoder, m http.Header) error {
return enc.WriteToken(jsontext.EndObject)
}

// HTTPHeaderUnmarshal is a custom unmarshaler for http.Header, unmarshaling values as single strings.
// HTTPHeaderUnmarshal is a custom unmarshaler for http.Header, unmarshaling values as single strings or, as other tools
// record them, lists of strings.
func HTTPHeaderUnmarshal(dec *jsontext.Decoder, h *http.Header) error {
tkn, err := dec.ReadToken()
if err != nil {
Expand Down Expand Up @@ -73,14 +74,39 @@ func HTTPHeaderUnmarshal(dec *jsontext.Decoder, h *http.Header) error {
return err
}

if val.Kind() != jsontext.KindString {
switch val.Kind() {
case jsontext.KindString:
h.Set(key, val.String())
case jsontext.KindBeginArray:
if err := headerValues(dec, h, key); err != nil {
return err
}
default:
return fmt.Errorf("expected string value, got %s", val.Kind())
}

h.Set(key, val.String())
}

_, err = dec.ReadToken() // consume jsontext.KindEndObject

return err
}

// headerValues adds the strings of a list, whose start dec has read, to h under key.
func headerValues(dec *jsontext.Decoder, h *http.Header, key string) error {
for dec.PeekKind() != jsontext.KindEndArray {
v, err := dec.ReadToken()
if err != nil {
return err
}

if v.Kind() != jsontext.KindString {
return fmt.Errorf("expected string value, got %s", v.Kind())
}

h.Add(key, v.String())
}

_, err := dec.ReadToken() // consume jsontext.KindEndArray

return err
}
17 changes: 17 additions & 0 deletions http_header_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,23 @@ func TestHTTPHeader(t *testing.T) {
}
})

// Other tools record a header's values as a list.
t.Run("a list of values", func(t *testing.T) {
out := http.Header{}
if err := json.Unmarshal([]byte(`{"Content-Type":["text/xml;charset=UTF-8"],"Vary":["Accept","Origin"]}`), &out, jsonOpts); err != nil {
t.Fatal(err)
}

want := http.Header{"Content-Type": {"text/xml;charset=UTF-8"}, "Vary": {"Accept", "Origin"}}
if !maps.EqualFunc(want, out, slices.Equal) {
t.Fatalf("want: %v, got: %v", want, out)
}

if err := json.Unmarshal([]byte(`{"Vary":["Accept",3]}`), &out, jsonOpts); err == nil {
t.Fatal("a list holding a number was read")
}
})

for i, tc := range []struct {
in http.Header
out string
Expand Down
Loading