diff --git a/context.go b/context.go index 34030a4..b514307 100644 --- a/context.go +++ b/context.go @@ -2,6 +2,7 @@ package gin import ( "context" + "fmt" "net/http/httptest" "time" @@ -41,8 +42,8 @@ func (c *Context) Response() http.ContextResponse { return NewContextResponse(c.instance, &BodyWriter{ResponseWriter: c.instance.Writer}) } -func (c *Context) WithValue(key string, value any) { - c.instance.Set(key, value) +func (c *Context) WithValue(key any, value any) { + c.instance.Set(fmt.Sprintf("%v", key), value) } func (c *Context) Context() context.Context { diff --git a/context_test.go b/context_test.go index 6d0427f..c66a95a 100644 --- a/context_test.go +++ b/context_test.go @@ -7,10 +7,19 @@ import ( ) func TestContext(t *testing.T) { + type customKeyType struct{} + var customKey customKeyType + httpCtx := Background() httpCtx.WithValue("Hello", "world") httpCtx.WithValue("Hi", "Goravel") + httpCtx.WithValue(1, "one") + httpCtx.WithValue(1.1, "one point one") + httpCtx.WithValue(customKey, "hello") ctx := httpCtx.Context() assert.Equal(t, ctx.Value("Hello").(string), "world") assert.Equal(t, ctx.Value("Hi").(string), "Goravel") + assert.Equal(t, ctx.Value(1).(string), "one") + assert.Equal(t, ctx.Value(1.1).(string), "one point one") + assert.Equal(t, ctx.Value(customKey), "hello") }