diff --git a/message.go b/message.go index 630ad2f..e96cf5d 100644 --- a/message.go +++ b/message.go @@ -404,6 +404,26 @@ func (m *Message) SetPath(s []string) { m.SetOption(URIPath, s) } +// Query gets the Query set on this message if any. +func (m Message) Query() []string { + return m.optionStrings(URIQuery) +} + +// QueryString gets a path as an ampersand separated string. +func (m Message) QueryString() string { + return strings.Join(m.Query(), "&") +} + +// SetQueryString sets a query by an ampersand separated string. +func (m *Message) SetQueryString(s string) { + m.SetQuery(strings.Split(s, "&")) +} + +// SetQuery updates or adds a URIQuery attribute on this message. +func (m *Message) SetQuery(s []string) { + m.SetOption(URIQuery, s) +} + // RemoveOption removes all references to an option func (m *Message) RemoveOption(opID OptionID) { m.opts = m.opts.Minus(opID) diff --git a/message_test.go b/message_test.go index 7cf7651..8969dad 100644 --- a/message_test.go +++ b/message_test.go @@ -405,6 +405,34 @@ func TestEncodeSeveral(t *testing.T) { } } +func TestEncodeManyQueries(t *testing.T) { + tests := map[string][]string{ + "a": []string{"a"}, + "axe": []string{"axe"}, + "a&b&c&d&e&f&h&g&i&j": []string{"a", "b", "c", "d", "e", + "f", "h", "g", "i", "j"}, + } + for p, a := range tests { + m := &Message{Type: Confirmable, Code: GET, MessageID: 12345} + m.SetQueryString(p) + b, err := m.MarshalBinary() + if err != nil { + t.Errorf("Error encoding %#v", p) + t.Fail() + continue + } + m2, err := ParseMessage(b) + if err != nil { + t.Fatalf("Can't parse my own message at %#v: %v", p, err) + } + + if !reflect.DeepEqual(m2.Query(), a) { + t.Errorf("Expected %#v, got %#v", a, m2.Path()) + t.Fail() + } + } +} + func TestPathAsOption(t *testing.T) { m := &Message{Type: Confirmable, Code: GET, MessageID: 12345} m.SetOption(LocationPath, []string{"a", "b"})