Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ref: use Sprintf as helper to accept type any for the key of WithValue #87

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gin

import (
"context"
"fmt"
"net/http/httptest"
"time"

Expand Down Expand Up @@ -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 {
Expand Down
13 changes: 13 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,16 @@ func TestContext(t *testing.T) {
assert.Equal(t, ctx.Value("Hello").(string), "world")
assert.Equal(t, ctx.Value("Hi").(string), "Goravel")
}

func TestContextWithCustomKeyType(t *testing.T) {
type customKeyType struct{}
var customKey customKeyType
var customKeyTwo customKeyType
mdanialr marked this conversation as resolved.
Show resolved Hide resolved

httpCtx := Background()
httpCtx.WithValue(customKey, "hello")
httpCtx.WithValue(customKeyTwo, "world")

assert.Equal(t, httpCtx.Value(customKey), "hello")
assert.Equal(t, httpCtx.Value(customKeyTwo), "world")
}