metadata: allow to Set/Del multiple items

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2022-05-03 15:19:10 +03:00
parent b433cbcbb6
commit d4efbb9b22
2 changed files with 30 additions and 15 deletions

View File

@ -76,16 +76,23 @@ func (md Metadata) Get(key string) (string, bool) {
} }
// Set is used to store value in metadata // Set is used to store value in metadata
func (md Metadata) Set(key, val string) { func (md Metadata) Set(kv ...string) {
md[textproto.CanonicalMIMEHeaderKey(key)] = val if len(kv)%2 == 1 {
kv = kv[:len(kv)-1]
}
for idx := 0; idx < len(kv); idx += 2 {
md[textproto.CanonicalMIMEHeaderKey(kv[idx])] = kv[idx+1]
}
} }
// Del is used to remove value from metadata // Del is used to remove value from metadata
func (md Metadata) Del(key string) { func (md Metadata) Del(keys ...string) {
for _, key := range keys {
// fast path // fast path
delete(md, key) delete(md, key)
// slow path // slow path
delete(md, textproto.CanonicalMIMEHeaderKey(key)) delete(md, textproto.CanonicalMIMEHeaderKey(key))
}
} }
// Copy makes a copy of the metadata // Copy makes a copy of the metadata
@ -129,13 +136,6 @@ func Pairs(kv ...string) (Metadata, bool) {
return nil, false return nil, false
} }
md := New(len(kv) / 2) md := New(len(kv) / 2)
var k string md.Set(kv...)
for i, v := range kv {
if i%2 == 0 {
k = v
continue
}
md.Set(k, v)
}
return md, true return md, true
} }

View File

@ -5,6 +5,21 @@ import (
"testing" "testing"
) )
func TestMetadataSetMultiple(t *testing.T) {
md := New(4)
md.Set("key1", "val1", "key2", "val2", "key3")
if v, ok := md.Get("key1"); !ok || v != "val1" {
t.Fatalf("invalid kv %#+v", md)
}
if v, ok := md.Get("key2"); !ok || v != "val2" {
t.Fatalf("invalid kv %#+v", md)
}
if _, ok := md.Get("key3"); ok {
t.Fatalf("invalid kv %#+v", md)
}
}
func TestAppend(t *testing.T) { func TestAppend(t *testing.T) {
ctx := context.Background() ctx := context.Background()
ctx = AppendIncomingContext(ctx, "key1", "val1", "key2", "val2") ctx = AppendIncomingContext(ctx, "key1", "val1", "key2", "val2")