Add context.Join instead

This commit is contained in:
Michael Darakananda
2016-09-23 11:12:52 +10:00
parent 164a9d0a3e
commit b32ff19331
2 changed files with 14 additions and 22 deletions

View File

@ -117,10 +117,13 @@ func (md MD) Len() int {
// Copy returns a copy of md. // Copy returns a copy of md.
func (md MD) Copy() MD { func (md MD) Copy() MD {
return join(md) return Join(md)
} }
func join(mds ...MD) MD { // Join joins any number of MDs into a single MD.
// The order of values for each key is determined by the order in which
// the MDs containing those values are presented to Join.
func Join(mds ...MD) MD {
out := MD{} out := MD{}
for _, md := range mds { for _, md := range mds {
for k, v := range md { for k, v := range md {
@ -134,9 +137,6 @@ type mdKey struct{}
// NewContext creates a new context with md attached. // NewContext creates a new context with md attached.
func NewContext(ctx context.Context, md MD) context.Context { 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) return context.WithValue(ctx, mdKey{}, md)
} }

View File

@ -36,8 +36,6 @@ package metadata
import ( import (
"reflect" "reflect"
"testing" "testing"
"golang.org/x/net/context"
) )
const binaryValue = string(128) const binaryValue = string(128)
@ -123,24 +121,18 @@ func TestCopy(t *testing.T) {
} }
} }
func TestContext(t *testing.T) { func TestJoin(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 { for _, test := range []struct {
add, want MD mds []MD
want MD
}{ }{
{Pairs("foo", "bar"), Pairs("foo", "bar")}, {[]MD{}, MD{}},
{Pairs("foo", "baz"), Pairs("foo", "bar", "foo", "baz")}, {[]MD{Pairs("foo", "bar")}, Pairs("foo", "bar")},
{Pairs("zip", "zap"), Pairs("foo", "bar", "foo", "baz", "zip", "zap")}, {[]MD{Pairs("foo", "bar"), Pairs("foo", "baz")}, Pairs("foo", "bar", "foo", "baz")},
{[]MD{Pairs("foo", "bar"), Pairs("foo", "baz"), Pairs("zip", "zap")}, Pairs("foo", "bar", "foo", "baz", "zip", "zap")},
} { } {
ctx = NewContext(ctx, test.add) md := Join(test.mds...)
md, ok := FromContext(ctx) if !reflect.DeepEqual(md, test.want) {
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) t.Errorf("context's metadata is %v, want %v", md, test.want)
} }
} }