-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcontext.go
More file actions
102 lines (81 loc) · 1.86 KB
/
context.go
File metadata and controls
102 lines (81 loc) · 1.86 KB
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
100
101
102
package fox
import (
"bytes"
"io"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/fox-gonic/fox/logger"
)
// Context with engine
type Context struct {
*gin.Context
engine *Engine
Logger logger.Logger
// Request is the http request copy from gin.Context.
Request *http.Request
}
// RequestBody return request body bytes
// see c.ShouldBindBodyWith
func (c *Context) RequestBody() (body []byte, err error) {
if cb, ok := c.Get(gin.BodyBytesKey); ok {
if cbb, ok := cb.([]byte); ok {
body = cbb
}
}
if body == nil && c.Request != nil && c.Request.Body != nil {
var (
buf bytes.Buffer
bodyR = io.TeeReader(c.Request.Body, &buf)
)
if body, err = io.ReadAll(bodyR); err != nil {
return body, err
}
c.Set(gin.BodyBytesKey, body)
// copy the request body to the next handler
c.Request.Body = io.NopCloser(&buf)
}
return body, err
}
// TraceID return request id
func (c *Context) TraceID() string {
if id, exists := c.Get(logger.TraceID); exists {
return id.(string)
}
if id := c.GetHeader(logger.TraceID); len(id) > 0 {
return id
}
if id := c.Context.Writer.Header().Get(logger.TraceID); len(id) > 0 {
return id
}
id := logger.DefaultGenRequestID()
c.Header(logger.TraceID, id)
c.Set(logger.TraceID, id)
return id
}
func (c *Context) Done() <-chan struct{} {
return c.Request.Context().Done()
}
func (c *Context) Err() error {
return c.Request.Context().Err()
}
func (c *Context) Value(key any) any {
return c.Request.Context().Value(key)
}
func (c *Context) Deadline() (deadline time.Time, ok bool) {
return c.Request.Context().Deadline()
}
func (c *Context) Next() {
c.Context.Request = c.Request
c.Context.Next()
}
func (c *Context) Copy() *Context {
ginCtx := c.Context.Copy()
ginCtx.Request = c.Request
return &Context{
Context: ginCtx,
engine: c.engine,
Logger: c.Logger,
Request: c.Request,
}
}