Skip to content

Commit

Permalink
Refactor Locals function and add new test case
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanbekhen committed Jan 28, 2024
1 parent d03023e commit db19a35
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 7 deletions.
10 changes: 3 additions & 7 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -820,14 +820,10 @@ func (c *DefaultCtx) Locals(key any, value ...any) any {
// Locals function utilizing Go's generics feature.
// This function allows for manipulating and retrieving local values within a request context with a more specific data type.
func Locals[V any](c Ctx, key any, value ...any) V {
ctx, ok := c.(*DefaultCtx)
if !ok {
panic(fmt.Errorf("failed to type-assert to *DefaultCtx"))
}
var v V
v, ok = ctx.Locals(key, value...).(V)
v, ok := c.Locals(key, value...).(V)
if !ok {
panic(fmt.Errorf("failed to type-assert to %T", v))
// return zero value of type V
return v
}
return v
}
Expand Down
1 change: 1 addition & 0 deletions ctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1771,6 +1771,7 @@ func Test_Ctx_Locals_Generic(t *testing.T) {
require.Equal(t, "doe", Locals[string](c, "john"))
require.Equal(t, 18, Locals[int](c, "age"))
require.Equal(t, true, Locals[bool](c, "isHuman"))
require.Equal(t, 0, Locals[int](c, "isHuman"))
return nil
})
resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", nil))
Expand Down

0 comments on commit db19a35

Please sign in to comment.