metadata.NewContext merges old metadata

Previously metadata.NewContext(ctx, md) replaces whatever metadata in
ctx with md.
This patch merges the old metadata with md before returning the new
context.

Fixes #902.
This commit is contained in:
Michael Darakananda
2016-09-22 16:58:16 +10:00
parent 71d2ea4f75
commit 164a9d0a3e
2 changed files with 48 additions and 3 deletions

View File

@ -117,10 +117,14 @@ func (md MD) Len() int {
// Copy returns a copy of md.
func (md MD) Copy() MD {
return join(md)
}
func join(mds ...MD) MD {
out := MD{}
for k, v := range md {
for _, i := range v {
out[k] = append(out[k], i)
for _, md := range mds {
for k, v := range md {
out[k] = append(out[k], v...)
}
}
return out
@ -130,6 +134,9 @@ type mdKey struct{}
// NewContext creates a new context with md attached.
func NewContext(ctx context.Context, md MD) context.Context {
if old, ok := FromContext(ctx); ok {
return context.WithValue(ctx, mdKey{}, join(old, md))
}
return context.WithValue(ctx, mdKey{}, md)
}

View File

@ -36,6 +36,8 @@ package metadata
import (
"reflect"
"testing"
"golang.org/x/net/context"
)
const binaryValue = string(128)
@ -107,3 +109,39 @@ func TestPairsMD(t *testing.T) {
}
}
}
func TestCopy(t *testing.T) {
const key, val = "key", "val"
orig := Pairs(key, val)
copy := orig.Copy()
if !reflect.DeepEqual(orig, copy) {
t.Errorf("copied value not equal to the original, got %v, want %v", copy, orig)
}
orig[key][0] = "foo"
if v := copy[key][0]; v != val {
t.Errorf("change in original should not affect copy, got %q, want %q", v, val)
}
}
func TestContext(t *testing.T) {
ctx := context.Background()
if md, ok := FromContext(ctx); len(md) != 0 || ok {
t.Errorf("found (%v, %t), want (%v, %t)", md, ok, nil, false)
}
for _, test := range []struct {
add, want MD
}{
{Pairs("foo", "bar"), Pairs("foo", "bar")},
{Pairs("foo", "baz"), Pairs("foo", "bar", "foo", "baz")},
{Pairs("zip", "zap"), Pairs("foo", "bar", "foo", "baz", "zip", "zap")},
} {
ctx = NewContext(ctx, test.add)
md, ok := FromContext(ctx)
if !ok {
t.Errorf("context missing metadata after adding %v", test.add)
} else if !reflect.DeepEqual(md, test.want) {
t.Errorf("context's metadata is %v, want %v", md, test.want)
}
}
}