-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhttpContext.go
More file actions
154 lines (138 loc) · 5.63 KB
/
Copy pathhttpContext.go
File metadata and controls
154 lines (138 loc) · 5.63 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package context
import (
"net/http"
"reflect"
"strings"
"github.com/farseer-go/collections"
"github.com/farseer-go/fs/asyncLocal"
"github.com/farseer-go/webapi/check"
"golang.org/x/net/websocket"
)
var RoutineHttpContext = asyncLocal.New[*HttpContext]()
type HttpContext struct {
WebsocketConn *websocket.Conn // websocket
Request *HttpRequest // Request
Response *HttpResponse // Response
Header collections.ReadonlyDictionary[string, string] // 头部信息
ResponseHeader collections.ReadonlyDictionary[string, string] // 头部信息
Cookie *HttpCookies // Cookies信息
Session IHttpSession // Session信息
Route *HttpRoute // 路由信息
URI *HttpURL // URL信息
Data *HttpData // 用于传递值
Method string // 客户端提交时的Method
ContentLength int64 // 客户端提交时的内容长度
ContentType string // 客户端提交时的内容类型
Exception error // 是否发生异常
Jwt *HttpJwt // jwt验证
Close bool
TransferEncoding []string
headerMap map[string]string // 请求头的明文map缓存,构造时生成一次,供链路追踪等复用,避免重复ToMap分配
}
// HeaderMap 返回请求头的明文map(构造时已生成,直接复用,避免每请求重复ToMap分配)
func (receiver *HttpContext) HeaderMap() map[string]string {
return receiver.headerMap
}
// NewHttpContext 初始化上下文
func NewHttpContext(httpRoute *HttpRoute, w http.ResponseWriter, r *http.Request) *HttpContext {
var httpContext = HttpContext{
Request: &HttpRequest{
Body: r.Body,
R: r,
Form: make(map[string]any),
Query: make(map[string]any),
},
Response: &HttpResponse{
W: w,
statusMessage: "成功",
},
URI: &HttpURL{
Path: r.URL.Path,
RemoteAddr: r.RemoteAddr,
X_Forwarded_For: r.Header.Get("X-Forwarded-For"),
X_Real_Ip: r.Header.Get("X-Real-Ip"),
Cf_Connecting_Ip: r.Header.Get("Cf-Connecting-Ip"),
Host: r.Host,
Proto: r.Proto,
RequestURI: r.RequestURI,
QueryString: r.URL.RawQuery,
Query: make(map[string]any),
Url: "http://" + r.Host + r.RequestURI, // 先默认https,后边在处理
R: r,
},
Data: &HttpData{value: collections.NewDictionary[string, any]()},
Method: r.Method,
ContentLength: r.ContentLength,
Close: r.Close,
TransferEncoding: r.TransferEncoding,
ContentType: "",
Route: httpRoute,
Cookie: initCookies(w, r),
Jwt: &HttpJwt{
w: w,
r: r,
},
}
if httpRoute.Schema == "ws" {
if r.TLS != nil {
httpContext.URI.Url = "wss://" + r.Host + r.RequestURI
} else {
httpContext.URI.Url = "ws://" + r.Host + r.RequestURI
}
} else if r.TLS != nil {
httpContext.URI.Url = "https://" + r.Host + r.RequestURI
}
// header:先组装成明文map(缓存复用),再转成只读字典,避免后续ToMap重复分配
headerMap := make(map[string]string, len(r.Header))
for k, v := range r.Header {
headerMap[k] = strings.Join(v, ";")
}
httpContext.headerMap = headerMap
httpContext.Header = collections.NewReadonlyDictionaryFromMap(headerMap)
// ContentType
for _, contentType := range strings.Split(httpContext.Header.GetValue("Content-Type"), ";") {
if strings.Contains(contentType, "/") {
httpContext.ContentType = contentType
}
}
return &httpContext
}
func (receiver *HttpContext) SetWebsocket(conn *websocket.Conn) {
receiver.WebsocketConn = conn
}
// ParseParams 转换成Handle函数需要的参数
func (receiver *HttpContext) ParseParams() []reflect.Value {
// 没有入参时,忽略request.body
if receiver.Route.RequestParamType.Count() == 0 {
return []reflect.Value{}
}
if receiver.Route.Schema == "ws" {
contextWebSocket := reflect.New(receiver.Route.RequestParamType.First().Elem())
contextWebSocket.MethodByName("SetContext").Call([]reflect.Value{reflect.ValueOf(receiver)})
// 第2个参数起,为interface类型,需要做注入操作
return receiver.Route.parseInterfaceParam([]reflect.Value{contextWebSocket})
}
if receiver.Method == "GET" {
return receiver.Route.FormToParams(receiver.Request.Query)
}
switch receiver.ContentType {
case "application/json":
return receiver.Route.JsonToParams(receiver.Request)
case "application/x-msgpack":
return receiver.Route.MsgpackToParams(receiver.Request)
default: //case "application/x-www-form-urlencoded", "multipart/form-data":
return receiver.Route.FormToParams(receiver.Request.Query) // Query比Form有更齐全的值,所以不用Form
}
}
// IsActionResult 是否为ActionResult类型
func (receiver *HttpContext) IsActionResult() bool {
return receiver.Route.ResponseBodyType.Count() == 1 && receiver.Route.ResponseBodyType.First().String() == "action.IResult"
}
// RequestParamCheck 实现了check.ICheck(必须放在过滤器之后执行)
func (receiver *HttpContext) RequestParamCheck() {
if receiver.Route.RequestParamIsImplCheck {
dto := receiver.Request.Params[0]
val := dto.Addr().Interface()
val.(check.ICheck).Check()
}
}