metadata: add Pairs helper func
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
parent
b505455f7c
commit
3247da3dd0
@ -108,7 +108,11 @@ func NewOutgoingContext(ctx context.Context, md Metadata) context.Context {
|
||||
}
|
||||
|
||||
// AppendOutgoingContext apends new md to context
|
||||
func AppendOutgoingContext(ctx context.Context, md Metadata) context.Context {
|
||||
func AppendOutgoingContext(ctx context.Context, kv ...string) context.Context {
|
||||
md, ok := Pairs(kv...)
|
||||
if !ok {
|
||||
return ctx
|
||||
}
|
||||
omd, ok := FromOutgoingContext(ctx)
|
||||
if !ok {
|
||||
return NewOutgoingContext(ctx, md)
|
||||
@ -120,7 +124,11 @@ func AppendOutgoingContext(ctx context.Context, md Metadata) context.Context {
|
||||
}
|
||||
|
||||
// AppendIncomingContext apends new md to context
|
||||
func AppendIncomingContext(ctx context.Context, md Metadata) context.Context {
|
||||
func AppendIncomingContext(ctx context.Context, kv ...string) context.Context {
|
||||
md, ok := Pairs(kv...)
|
||||
if !ok {
|
||||
return ctx
|
||||
}
|
||||
omd, ok := FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return NewIncomingContext(ctx, md)
|
||||
|
@ -111,3 +111,19 @@ func Merge(omd Metadata, mmd Metadata, overwrite bool) Metadata {
|
||||
}
|
||||
return nmd
|
||||
}
|
||||
|
||||
func Pairs(kv ...string) (Metadata, bool) {
|
||||
if len(kv)%2 == 1 {
|
||||
return nil, false
|
||||
}
|
||||
md := New(len(kv) / 2)
|
||||
var k string
|
||||
for i, v := range kv {
|
||||
if i%2 == 0 {
|
||||
k = v
|
||||
continue
|
||||
}
|
||||
md.Set(k, v)
|
||||
}
|
||||
return md, true
|
||||
}
|
||||
|
@ -5,6 +5,28 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAppend(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx = AppendIncomingContext(ctx, "key1", "val1", "key2", "val2")
|
||||
md, ok := FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
t.Fatal("metadata empty")
|
||||
}
|
||||
if _, ok := md.Get("key1"); !ok {
|
||||
t.Fatal("key1 not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPairs(t *testing.T) {
|
||||
md, ok := Pairs("key1", "val1", "key2", "val2")
|
||||
if !ok {
|
||||
t.Fatal("odd number of kv")
|
||||
}
|
||||
if _, ok = md.Get("key1"); !ok {
|
||||
t.Fatal("key1 not found")
|
||||
}
|
||||
}
|
||||
|
||||
func testCtx(ctx context.Context) {
|
||||
md := New(2)
|
||||
md.Set("Key1", "Val1_new")
|
||||
|
Loading…
Reference in New Issue
Block a user