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 any as the key type WithValue #102

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
8 changes: 1 addition & 7 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ type Context struct {
request http.ContextRequest
}

type ctxKey string

func NewContext(ctx *fiber.Ctx) http.Context {
return &Context{instance: ctx}
}
Expand Down Expand Up @@ -61,11 +59,7 @@ func (c *Context) Err() error {
}

func (c *Context) Value(key any) any {
if keyStr, ok := key.(string); ok {
return c.instance.UserContext().Value(ctxKey(keyStr))
}

return nil
return c.instance.UserContext().Value(key)
}

func (c *Context) Instance() *fiber.Ctx {
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, httpCtx.Value("Hello").(string), "world")
assert.Equal(t, httpCtx.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")
}