From: Brad Fitzpatrick Date: Fri, 29 Apr 2016 03:04:30 +0000 (-0500) Subject: context: produce a nicer panic message for a nil WithValue key X-Git-Tag: go1.7beta1~412 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=c884f6594a594d2d18c4d21106592bd3cdfcbe9b;p=gostls13.git context: produce a nicer panic message for a nil WithValue key Change-Id: I2e8ae403622ba7131cadaba506100d79613183f1 Reviewed-on: https://go-review.googlesource.com/22601 Reviewed-by: Russ Cox Reviewed-by: Andrew Gerrand --- diff --git a/src/context/context.go b/src/context/context.go index da294b1292..5184b94e51 100644 --- a/src/context/context.go +++ b/src/context/context.go @@ -428,6 +428,9 @@ func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { // // The provided key must be comparable. func WithValue(parent Context, key, val interface{}) Context { + if key == nil { + panic("nil key") + } if !reflect.TypeOf(key).Comparable() { panic("key is not comparable") } diff --git a/src/context/context_test.go b/src/context/context_test.go index aa26161d2b..99456b188d 100644 --- a/src/context/context_test.go +++ b/src/context/context_test.go @@ -583,6 +583,10 @@ func TestWithValueChecksKey(t *testing.T) { if panicVal == nil { t.Error("expected panic") } + panicVal = recoveredValue(func() { WithValue(Background(), nil, "bar") }) + if got, want := fmt.Sprint(panicVal), "nil key"; got != want { + t.Errorf("panic = %q; want %q", got, want) + } } func recoveredValue(fn func()) (v interface{}) {