Copy metadata

This commit is contained in:
Asim Aslam 2019-01-17 09:40:49 +00:00
parent 7b89b36e37
commit 617db003d4
3 changed files with 27 additions and 8 deletions

View File

@ -12,6 +12,14 @@ type metaKey struct{}
// from Transport headers. // from Transport headers.
type Metadata map[string]string type Metadata map[string]string
func Copy(md Metadata) Metadata {
cmd := make(Metadata)
for k, v := range md {
cmd[k] = v
}
return cmd
}
func FromContext(ctx context.Context) (Metadata, bool) { func FromContext(ctx context.Context) (Metadata, bool) {
md, ok := ctx.Value(metaKey{}).(Metadata) md, ok := ctx.Value(metaKey{}).(Metadata)
return md, ok return md, ok

View File

@ -5,6 +5,21 @@ import (
"testing" "testing"
) )
func TestMetadataCopy(t *testing.T) {
md := Metadata{
"foo": "bar",
"bar": "baz",
}
cp := Copy(md)
for k, v := range md {
if cv := cp[k]; cv != v {
t.Fatalf("Got %s:%s for %s:%s", k, cv, k, v)
}
}
}
func TestMetadataContext(t *testing.T) { func TestMetadataContext(t *testing.T) {
md := Metadata{ md := Metadata{
"foo": "bar", "foo": "bar",

View File

@ -13,15 +13,11 @@ type clientWrapper struct {
} }
func (c *clientWrapper) setHeaders(ctx context.Context) context.Context { func (c *clientWrapper) setHeaders(ctx context.Context) context.Context {
md := make(metadata.Metadata) // copy metadata
mda, _ := metadata.FromContext(ctx)
if mda, ok := metadata.FromContext(ctx); ok { md := metadata.Copy(mda)
// make copy of metadata
for k, v := range mda {
md[k] = v
}
}
// set headers
for k, v := range c.headers { for k, v := range c.headers {
if _, ok := md[k]; !ok { if _, ok := md[k]; !ok {
md[k] = v md[k] = v