From 51fbff3e4aeb27dfcefbb6a709d4d6000d1dd756 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Tue, 10 Nov 2020 10:57:33 +0300 Subject: [PATCH] metadata: add checks for nil context Signed-off-by: Vasiliy Tolstov --- metadata/metadata.go | 6 ++++++ metadata/metadata_test.go | 9 +++++++++ 2 files changed, 15 insertions(+) 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",