diff --git a/metadata/metadata.go b/metadata/metadata.go index 1165bc95..b2216217 100644 --- a/metadata/metadata.go +++ b/metadata/metadata.go @@ -84,6 +84,9 @@ func Get(ctx context.Context, key string) (string, bool) { // FromContext returns metadata from the given context func FromContext(ctx context.Context) (Metadata, bool) { + if ctx == nil { + return nil, false + } md, ok := ctx.Value(metadataKey{}).(Metadata) if !ok { return nil, ok @@ -102,6 +105,9 @@ func New(size int) Metadata { // NewContext creates a new context with the given metadata func NewContext(ctx context.Context, md Metadata) context.Context { + if ctx == nil { + ctx = context.Background() + } return context.WithValue(ctx, metadataKey{}, Copy(md)) } diff --git a/metadata/metadata_test.go b/metadata/metadata_test.go index 2351eb37..56f56e54 100644 --- a/metadata/metadata_test.go +++ b/metadata/metadata_test.go @@ -63,6 +63,15 @@ func TestMetadataDelete(t *testing.T) { } +func TestNilContext(t *testing.T) { + var ctx context.Context + + _, ok := FromContext(ctx) + if ok { + t.Fatal("nil context") + } +} + func TestMetadataCopy(t *testing.T) { md := Metadata{ "Foo": "bar",