Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds a keys method to the NATS message header #1573

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions nats.go
Expand Up @@ -3640,6 +3640,17 @@ func (h Header) Get(key string) string {
return _EMPTY_
}

// Returns the list of keys in the message header
func (h Header) Keys() []string {
keys := make([]string, len(h))
i := 0
for k := range h {
keys[i] = k
i++
}
return keys
}

// Values returns all values associated with the given key.
// It is case-sensitive.
func (h Header) Values(key string) []string {
Expand Down
20 changes: 20 additions & 0 deletions nats_test.go
Expand Up @@ -29,6 +29,7 @@ import (
"reflect"
"regexp"
"runtime"
"slices"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -1593,6 +1594,25 @@ func TestHeaderParser(t *testing.T) {
checkStatus("NATS/1.0 404 No Messages", 404, "No Messages")
}

func TestHeaderKeys(t *testing.T) {
m := NewMsg("testing")
m.Header = Header{
"field1": []string{"a"},
"field2": []string{"b"},
}
actualKeys := m.Header.Keys()
if !slices.Contains(actualKeys, "field1") ||
!slices.Contains(actualKeys, "field2") {
t.Fatalf("Keys did not return expected list: %+v", actualKeys)
}

m.Header = Header{}
emptyKeys := m.Header.Keys()
if len(emptyKeys) > 0 {
t.Fatal("Empty header should've returned empty keys list")
}
}

func TestHeaderMultiLine(t *testing.T) {
m := NewMsg("foo")
m.Header = Header{
Expand Down