metadata: add checks for nil context
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
parent
be8d09c663
commit
51fbff3e4a
@ -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))
|
||||
}
|
||||
|
||||
|
@ -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",
|
||||
|
Loading…
x
Reference in New Issue
Block a user