Skip to content

Commit

Permalink
textproto: introduce Header.Values
Browse files Browse the repository at this point in the history
Same as textproto.MIMEHeader.Values in the stdlib [1].

The doc comment says the returned slice is read-only, but we actually do
a copy. This is so we don"t put ourselves into a corner and can change
how the function works internally in the future.

[1]: https://golang.org/pkg/net/textproto/#MIMEHeader.Values
  • Loading branch information
emersion committed Nov 25, 2020
1 parent f77964f commit 2b5070c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
18 changes: 17 additions & 1 deletion textproto/header.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ func (h *Header) Get(k string) string {
// The returned slice should not be modified and becomes invalid when the
// header is updated.
//
// Error is returned if header contains incorrect characters (RFC 6532)
// Error is returned if header contains incorrect characters (RFC 6532).
func (h *Header) Raw(k string) ([]byte, error) {
fields := h.m[textproto.CanonicalMIMEHeaderKey(k)]
if len(fields) == 0 {
Expand All @@ -150,6 +150,22 @@ func (h *Header) Raw(k string) ([]byte, error) {
return fields[len(fields)-1].raw()
}

// Values returns all values associated with the given key.
//
// The returned slice should not be modified and becomes invalid when the
// header is updated.
func (h *Header) Values(k string) []string {
fields := h.m[textproto.CanonicalMIMEHeaderKey(k)]
if len(fields) == 0 {
return nil
}
l := make([]string, len(fields))
for i, field := range fields {
l[len(fields)-i-1] = field.v
}
return l
}

// Set sets the header fields associated with key to the single field value.
// It replaces any existing values associated with key.
func (h *Header) Set(k, v string) {
Expand Down
8 changes: 8 additions & 0 deletions textproto/header_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,14 @@ func TestHeader(t *testing.T) {
if h.FieldsByKey("X-I-Dont-Exist").Next() {
t.Errorf("FieldsByKey(non-existing).Next() returned true, want false")
}

want = []string{
"from example.com by example.org",
"from localhost by example.com",
}
if l := h.Values("Received"); !reflect.DeepEqual(l, want) {
t.Errorf("Values(\"Received\") reported incorrect values: got \n%#v\n but want \n%#v", l, want)
}
}

func TestHeader_Set(t *testing.T) {
Expand Down

0 comments on commit 2b5070c

Please sign in to comment.