-
Notifications
You must be signed in to change notification settings - Fork 7
/
context.go
99 lines (78 loc) · 2.08 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package gin
import (
"context"
"net/http/httptest"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/goravel/framework/contracts/http"
)
const goravelContextKey = "goravel_contextKey"
func Background() http.Context {
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
return NewContext(ctx)
}
var contextPool = sync.Pool{New: func() any {
return &Context{}
}}
type Context struct {
instance *gin.Context
request http.ContextRequest
response http.ContextResponse
}
func NewContext(c *gin.Context) *Context {
ctx := contextPool.Get().(*Context)
ctx.instance = c
return ctx
}
func (c *Context) Request() http.ContextRequest {
if c.request == nil {
request := NewContextRequest(c, LogFacade, ValidationFacade)
c.request = request
}
return c.request
}
func (c *Context) Response() http.ContextResponse {
if c.response == nil {
response := NewContextResponse(c.instance, &BodyWriter{ResponseWriter: c.instance.Writer})
c.response = response
}
responseOrigin := c.Value("responseOrigin")
if responseOrigin != nil {
c.response.(*ContextResponse).origin = responseOrigin.(http.ResponseOrigin)
}
return c.response
}
func (c *Context) WithValue(key any, value any) {
goravelCtx := c.getGoravelCtx()
goravelCtx[key] = value
c.instance.Set(goravelContextKey, goravelCtx)
}
func (c *Context) WithContext(ctx context.Context) {
// Changing the request context to a new context
c.instance.Request = c.instance.Request.WithContext(ctx)
}
func (c *Context) Context() context.Context { return c }
func (c *Context) Deadline() (deadline time.Time, ok bool) {
return c.instance.Deadline()
}
func (c *Context) Done() <-chan struct{} {
return c.instance.Done()
}
func (c *Context) Err() error {
return c.instance.Err()
}
func (c *Context) Value(key any) any {
return c.getGoravelCtx()[key]
}
func (c *Context) Instance() *gin.Context {
return c.instance
}
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)
}