From: Joe Tsai Date: Sat, 13 Jan 2024 00:28:56 +0000 (-0800) Subject: context: improve valueCtx.String X-Git-Tag: go1.23rc1~1263 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=2057ad02bd8387378a2d1fd637e955e126f698bf;p=gostls13.git context: improve valueCtx.String Check for stringer on the key itself. This is useful for locally defined context key types, where there may be multiple instances of that type. For example, see http.contextKey, which can now be called after this change. For the value itself, print the type at least instead of just resorting to "". Change-Id: I588ef1df34e90fb9ebd83cb180fea495e1fedaa8 Reviewed-on: https://go-review.googlesource.com/c/go/+/555697 Reviewed-by: Damien Neil Reviewed-by: Dmitri Shuralyov Run-TryBot: Joseph Tsai LUCI-TryBot-Result: Go LUCI Auto-Submit: Joseph Tsai TryBot-Result: Gopher Robot --- diff --git a/src/context/context.go b/src/context/context.go index 80e1787576..1722ac87b8 100644 --- a/src/context/context.go +++ b/src/context/context.go @@ -740,13 +740,13 @@ func stringify(v any) string { case string: return s } - return "" + return reflectlite.TypeOf(v).String() } func (c *valueCtx) String() string { - return contextName(c.Context) + ".WithValue(type " + - reflectlite.TypeOf(c.key).String() + - ", val " + stringify(c.val) + ")" + return contextName(c.Context) + ".WithValue(" + + stringify(c.key) + ", " + + stringify(c.val) + ")" } func (c *valueCtx) Value(key any) any { diff --git a/src/context/x_test.go b/src/context/x_test.go index b1012fad87..e9b0576281 100644 --- a/src/context/x_test.go +++ b/src/context/x_test.go @@ -201,6 +201,8 @@ func TestCanceledTimeout(t *testing.T) { type key1 int type key2 int +func (k key2) String() string { return fmt.Sprintf("%[1]T(%[1]d)", k) } + var k1 = key1(1) var k2 = key2(1) // same int as k1, different type var k3 = key2(3) // same type as k2, different int @@ -224,13 +226,17 @@ func TestValues(t *testing.T) { c1 := WithValue(Background(), k1, "c1k1") check(c1, "c1", "c1k1", "", "") - if got, want := fmt.Sprint(c1), `context.Background.WithValue(type context_test.key1, val c1k1)`; got != want { + if got, want := fmt.Sprint(c1), `context.Background.WithValue(context_test.key1, c1k1)`; got != want { t.Errorf("c.String() = %q want %q", got, want) } c2 := WithValue(c1, k2, "c2k2") check(c2, "c2", "c1k1", "c2k2", "") + if got, want := fmt.Sprint(c2), `context.Background.WithValue(context_test.key1, c1k1).WithValue(context_test.key2(1), c2k2)`; got != want { + t.Errorf("c.String() = %q want %q", got, want) + } + c3 := WithValue(c2, k3, "c3k3") check(c3, "c2", "c1k1", "c2k2", "c3k3")