Skip to content

Commit

Permalink
refactor: change WithValue key type to any (#88)
Browse files Browse the repository at this point in the history
* bump version goravel framework

* ref: use any as the key type for WithValue

* test: more test cases for WithValue and Context

* test: swap the expected and actual value in assertion

* fix: need to store the key-val to underlying gin too

* test: remove type assert

* ref: immediately use `context.Context` as field ctx instead

* feat: helper to get goravel data from gin context

* ref: use helper to get goravel data from gin context instead

* test: add custom key to `WithValue` in group_test

* ref: remove the unnecessary ctx of `context.Context`
  • Loading branch information
mdanialr authored Sep 15, 2024
1 parent b7169e5 commit 3c0efad
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 21 deletions.
25 changes: 15 additions & 10 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"github.com/goravel/framework/contracts/http"
)

const goravelContextKey = "goravel_contextKey"

func Background() http.Context {
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
return NewContext(ctx)
Expand Down Expand Up @@ -41,18 +43,21 @@ 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) {
goravelCtx := c.getGoravelCtx()
goravelCtx[key] = value
c.instance.Set(goravelContextKey, goravelCtx)
}

func (c *Context) Context() context.Context {
ctx := context.Background()
for key, value := range c.instance.Keys {
// nolint
ctx = context.WithValue(ctx, key, value)
}
func (c *Context) Context() context.Context { return c }

return ctx
func (c *Context) getGoravelCtx() map[any]any {
if val, exist := c.instance.Get(goravelContextKey); exist {
if goravelCtxVal, ok := val.(map[any]any); ok {
return goravelCtxVal
}
}
return make(map[any]any)
}

func (c *Context) Deadline() (deadline time.Time, ok bool) {
Expand All @@ -68,7 +73,7 @@ func (c *Context) Err() error {
}

func (c *Context) Value(key any) any {
return c.instance.Value(key)
return c.getGoravelCtx()[key]
}

func (c *Context) Instance() *gin.Context {
Expand Down
20 changes: 18 additions & 2 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,26 @@ import (
)

func TestContext(t *testing.T) {
// even with the same underlying empty struct, Go will still distinguish between
// each type declaration
type customType struct{}
type anotherCustomType struct{}
var customTypeKey customType
var anotherCustomTypeKey anotherCustomType

httpCtx := Background()
httpCtx.WithValue("Hello", "world")
httpCtx.WithValue("Hi", "Goravel")
httpCtx.WithValue(customTypeKey, "halo")
httpCtx.WithValue(anotherCustomTypeKey, "hola")
httpCtx.WithValue(1, "one")
httpCtx.WithValue(2.2, "two point two")

ctx := httpCtx.Context()
assert.Equal(t, ctx.Value("Hello").(string), "world")
assert.Equal(t, ctx.Value("Hi").(string), "Goravel")
assert.Equal(t, "world", ctx.Value("Hello"))
assert.Equal(t, "Goravel", ctx.Value("Hi"))
assert.Equal(t, "halo", ctx.Value(customTypeKey))
assert.Equal(t, "hola", ctx.Value(anotherCustomTypeKey))
assert.Equal(t, "one", ctx.Value(1))
assert.Equal(t, "two point two", ctx.Value(2.2))
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.21
require (
github.com/gin-gonic/gin v1.10.0
github.com/gookit/validate v1.5.2
github.com/goravel/framework v1.14.5
github.com/goravel/framework v1.14.6-0.20240912145232-6543aeadf1bc
github.com/rs/cors v1.11.0
github.com/savioxavier/termlink v1.3.0
github.com/spf13/cast v1.6.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,8 @@ github.com/goravel/file-rotatelogs/v2 v2.4.2 h1:g68AzbePXcm0V2CpUMc9j4qVzcDn7+7a
github.com/goravel/file-rotatelogs/v2 v2.4.2/go.mod h1:23VuSW8cBS4ax5cmbV+5AaiLpq25b8UJ96IhbAkdo8I=
github.com/goravel/framework v1.14.5 h1:FItqxRGkBK0h/TIknF24TuMZCtBRaSr3DnQLEzhfvXc=
github.com/goravel/framework v1.14.5/go.mod h1:rScDXGQZdoVfyxemNPmijlz/2a+lWNOa4jTuak5GGVg=
github.com/goravel/framework v1.14.6-0.20240912145232-6543aeadf1bc h1:mWObAigy7PhrJkq1uK2KvV34JkTb8gIRxD8RU66MQVU=
github.com/goravel/framework v1.14.6-0.20240912145232-6543aeadf1bc/go.mod h1:rScDXGQZdoVfyxemNPmijlz/2a+lWNOa4jTuak5GGVg=
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI=
Expand Down
44 changes: 36 additions & 8 deletions group_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,10 @@ func TestGroup(t *testing.T) {

resource := resourceController{}
gin.GlobalMiddleware(func(ctx contractshttp.Context) {
type customKey struct{}
var customKeyCtx customKey
ctx.WithValue(customKeyCtx, "context with custom key")
ctx.WithValue(2.2, "two point two")
ctx.WithValue("action", "index")
ctx.Request().Next()
})
Expand All @@ -263,6 +267,10 @@ func TestGroup(t *testing.T) {

resource := resourceController{}
gin.GlobalMiddleware(func(ctx contractshttp.Context) {
type customKey struct{}
var customKeyCtx customKey
ctx.WithValue(customKeyCtx, "context with custom key")
ctx.WithValue(2.2, "two point two")
ctx.WithValue("action", "show")
ctx.Request().Next()
})
Expand All @@ -284,6 +292,10 @@ func TestGroup(t *testing.T) {

resource := resourceController{}
gin.GlobalMiddleware(func(ctx contractshttp.Context) {
type customKey struct{}
var customKeyCtx customKey
ctx.WithValue(customKeyCtx, "context with custom key")
ctx.WithValue(2.2, "two point two")
ctx.WithValue("action", "store")
ctx.Request().Next()
})
Expand All @@ -305,6 +317,10 @@ func TestGroup(t *testing.T) {

resource := resourceController{}
gin.GlobalMiddleware(func(ctx contractshttp.Context) {
type customKey struct{}
var customKeyCtx customKey
ctx.WithValue(customKeyCtx, "context with custom key")
ctx.WithValue(2.2, "two point two")
ctx.WithValue("action", "update")
ctx.Request().Next()
})
Expand All @@ -326,6 +342,10 @@ func TestGroup(t *testing.T) {

resource := resourceController{}
gin.GlobalMiddleware(func(ctx contractshttp.Context) {
type customKey struct{}
var customKeyCtx customKey
ctx.WithValue(customKeyCtx, "context with custom key")
ctx.WithValue(2.2, "two point two")
ctx.WithValue("action", "update")
ctx.Request().Next()
})
Expand All @@ -347,6 +367,10 @@ func TestGroup(t *testing.T) {

resource := resourceController{}
gin.GlobalMiddleware(func(ctx contractshttp.Context) {
type customKey struct{}
var customKeyCtx customKey
ctx.WithValue(customKeyCtx, "context with custom key")
ctx.WithValue(2.2, "two point two")
ctx.WithValue("action", "destroy")
ctx.Request().Next()
})
Expand Down Expand Up @@ -435,16 +459,16 @@ func TestGroup(t *testing.T) {
route2.Get("/middleware/{id}", func(ctx contractshttp.Context) contractshttp.Response {
return ctx.Response().Success().Json(contractshttp.Json{
"id": ctx.Request().Input("id"),
"ctx": ctx.Value("ctx").(string),
"ctx1": ctx.Value("ctx1").(string),
"ctx": ctx.Value("ctx"),
"ctx1": ctx.Value("ctx1"),
})
})
})
route1.Middleware(contextMiddleware2()).Get("/middleware/{id}", func(ctx contractshttp.Context) contractshttp.Response {
return ctx.Response().Success().Json(contractshttp.Json{
"id": ctx.Request().Input("id"),
"ctx": ctx.Value("ctx").(string),
"ctx2": ctx.Value("ctx2").(string),
"ctx": ctx.Value("ctx"),
"ctx2": ctx.Value("ctx2"),
})
})
})
Expand All @@ -462,16 +486,16 @@ func TestGroup(t *testing.T) {
route2.Get("/middleware/{id}", func(ctx contractshttp.Context) contractshttp.Response {
return ctx.Response().Success().Json(contractshttp.Json{
"id": ctx.Request().Input("id"),
"ctx": ctx.Value("ctx").(string),
"ctx1": ctx.Value("ctx1").(string),
"ctx": ctx.Value("ctx"),
"ctx1": ctx.Value("ctx1"),
})
})
})
route1.Middleware(contextMiddleware2()).Get("/middleware/{id}", func(ctx contractshttp.Context) contractshttp.Response {
return ctx.Response().Success().Json(contractshttp.Json{
"id": ctx.Request().Input("id"),
"ctx": ctx.Value("ctx").(string),
"ctx2": ctx.Value("ctx2").(string),
"ctx": ctx.Value("ctx"),
"ctx2": ctx.Value("ctx2"),
})
})
})
Expand Down Expand Up @@ -564,6 +588,9 @@ func abortMiddleware() contractshttp.Middleware {

func contextMiddleware() contractshttp.Middleware {
return func(ctx contractshttp.Context) {
type customKey struct{}
var customKeyCtx customKey
ctx.WithValue(customKeyCtx, "context with custom key")
ctx.WithValue("ctx", "Goravel")

ctx.Request().Next()
Expand All @@ -572,6 +599,7 @@ func contextMiddleware() contractshttp.Middleware {

func contextMiddleware1() contractshttp.Middleware {
return func(ctx contractshttp.Context) {
ctx.WithValue(2.2, "two point two")
ctx.WithValue("ctx1", "Hello")

ctx.Request().Next()
Expand Down

0 comments on commit 3c0efad

Please sign in to comment.