metadata: add checks for nil context

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2020-11-10 10:57:33 +03:00
parent be8d09c663
commit 51fbff3e4a
2 changed files with 15 additions and 0 deletions

View File

@ -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))
}

View File

@ -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",