-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctx.go
97 lines (81 loc) · 2.1 KB
/
ctx.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
package request
import (
"github.com/photowey/fastrouter/internal/pkg/pathx"
"github.com/photowey/fastrouter/pkg/collection"
"github.com/photowey/fastrouter/pkg/headermap"
"github.com/photowey/fastrouter/pkg/jsonx"
"github.com/photowey/fastrouter/pkg/nanoid"
"github.com/valyala/fasthttp"
)
const (
XForwardedFor = "X-Forwarded-For"
ContentType = "Content-Type"
emptyString = ""
defaultHeaderContent = "-"
)
const (
IdLength = 32
)
type Context struct {
Ip string
RequestId string
ContentType string
Path string
Method string
UserAgent string
HeaderMap headermap.HeaderMap
BodyMap collection.StringMap
HandleResponse bool
Header headermap.HeaderMap
StatusCode int
Body []byte
}
func (ctx Context) BuildMapping() string {
return pathx.BuildMapping(ctx.Method, ctx.Path)
}
func (ctx *Context) Response(body []byte) {
ctx.HandleResponse = true
ctx.Body = body
}
func (ctx *Context) ResponseJSON(body any) {
ctx.HandleResponse = true
ctx.Body = jsonx.Bytes(body)
}
func NewRequestContext(ctx *fasthttp.RequestCtx) *Context {
return &Context{
Ip: parseIp(ctx),
RequestId: buildRequestId(),
ContentType: parseContentType(ctx),
Path: parsePath(ctx),
Method: parseMethod(ctx),
UserAgent: parseUserAgent(ctx),
HeaderMap: headermap.NewHeaderMap(),
BodyMap: collection.NewStringMap(),
StatusCode: fasthttp.StatusOK,
}
}
func parsePath(ctx *fasthttp.RequestCtx) string {
return string(ctx.Path())
}
func parseMethod(ctx *fasthttp.RequestCtx) string {
return string(ctx.Method())
}
func parseUserAgent(ctx *fasthttp.RequestCtx) string {
return string(ctx.UserAgent())
}
func parseIp(ctx *fasthttp.RequestCtx) string {
ip := string(ctx.Request.Header.Peek(XForwardedFor))
if ip == emptyString {
ip = ctx.RemoteIP().String()
if ip == emptyString {
return defaultHeaderContent
}
}
return ip
}
func buildRequestId() string {
return nanoid.MustNew(IdLength)
}
func parseContentType(ctx *fasthttp.RequestCtx) string {
return string(ctx.Request.Header.Peek(ContentType))
}