From f1e92163a561624a19e9ef3f6115908e7e005899 Mon Sep 17 00:00:00 2001 From: Kevin Hoffman Date: Wed, 28 Feb 2024 10:06:44 -0500 Subject: [PATCH] adds a keys method to header Signed-off-by: Kevin Hoffman --- nats.go | 11 +++++++++++ nats_test.go | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/nats.go b/nats.go index 0be428932..3bd646662 100644 --- a/nats.go +++ b/nats.go @@ -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 { diff --git a/nats_test.go b/nats_test.go index 7dcdce2cf..a2f34d86a 100644 --- a/nats_test.go +++ b/nats_test.go @@ -29,6 +29,7 @@ import ( "reflect" "regexp" "runtime" + "slices" "strconv" "strings" "sync" @@ -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{