-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcontext.go
68 lines (51 loc) · 1.15 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
package fox
import (
"bytes"
"io"
"github.com/gin-gonic/gin"
"github.com/fox-gonic/fox/logger"
)
// Context with engine
type Context struct {
*gin.Context
engine *Engine
Logger logger.Logger
}
// 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
}
c.Set(gin.BodyBytesKey, body)
// copy the request body to the next handler
c.Request.Body = io.NopCloser(&buf)
}
return
}
// 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
}