-
Notifications
You must be signed in to change notification settings - Fork 15
/
HttpServ.go
1300 lines (1182 loc) · 34.6 KB
/
HttpServ.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
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package s
import (
"compress/gzip"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/ssgo/discover"
"github.com/ssgo/log"
"github.com/ssgo/standard"
"github.com/ssgo/u"
"golang.org/x/net/websocket"
)
//type Request struct {
// http.Request
// injects map[reflect.Type]any
//}
//
//// 设置一个生命周期在 Request 中的对象,请求中可以使用对象类型注入参数方便调用
//func (request *Request) SetInject(obj any) {
// if request.injects == nil {
// request.injects = map[reflect.Type]any{}
// }
// request.injects[reflect.TypeOf(obj)] = obj
//}
//
//// 获取本生命周期中指定类型的 Session 对象
//func (request *Request) GetInject(dataType reflect.Type) any {
// if request.injects == nil {
// return nil
// }
// return request.injects[dataType]
//}
//type Uploader struct {
// request *http.Request
//}
type UploadFile struct {
fileHeader *multipart.FileHeader
Filename string
Header textproto.MIMEHeader
Size int64
}
//func (uploader *Uploader) Fields() []string {
// fields := make([]string, 0)
// if uploader.request.MultipartForm != nil {
// for field := range uploader.request.MultipartForm.File {
// fields = append(fields, field)
// }
// }
// return fields
//}
//
//func (uploader *Uploader) File(field string) *UploadFile {
// uploadFiles := uploader.Files(field)
// if len(uploadFiles) > 0 {
// return uploadFiles[0]
// }
// return nil
//}
//
//func (uploader *Uploader) Files(field string) []*UploadFile {
// uploadFiles := make([]*UploadFile, 0)
// if uploader.request.MultipartForm != nil {
// if fileHeaders := uploader.request.MultipartForm.File[field]; fileHeaders != nil {
// for _, fileHeader := range fileHeaders {
// uploadFiles = append(uploadFiles, &UploadFile{
// fileHeader: fileHeader,
// Filename: fileHeader.Filename,
// Header: fileHeader.Header,
// Size: fileHeader.Size,
// })
// }
// }
// }
// return uploadFiles
//}
func (uploadFile *UploadFile) Open() (multipart.File, error) {
return uploadFile.fileHeader.Open()
}
func (uploadFile *UploadFile) Save(filename string) error {
u.CheckPath(filename)
if dstFile, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600); err == nil {
if srcFile, err := uploadFile.fileHeader.Open(); err == nil {
defer srcFile.Close()
io.Copy(dstFile, srcFile)
return nil
} else {
return err
}
} else {
return err
}
}
func (uploadFile *UploadFile) Content() ([]byte, error) {
if file, err := uploadFile.fileHeader.Open(); err == nil {
buf, err := io.ReadAll(file)
if err == nil {
return buf, nil
} else {
return nil, err
}
} else {
return nil, err
}
}
type Request struct {
*http.Request
contextValues map[string]any
Id string
}
func (request *Request) ResetPath(path string) {
request.RequestURI = path
if newUrl, err := url.Parse(path); err == nil {
request.URL = newUrl
}
}
func (request *Request) Set(key string, value any) {
request.contextValues[key] = value
}
func (request *Request) Get(key string) any {
return request.contextValues[key]
}
type Response struct {
Id string
Writer http.ResponseWriter
status int
outLen int
changed bool
headerWritten bool
dontLog200 bool
dontLogArgs []string
ProxyHeader *http.Header
}
type Logger = log.Logger
func MakeUrl(request *http.Request, path string) string {
return fmt.Sprint(request.Header.Get(standard.DiscoverHeaderScheme), "://", request.Header.Get(standard.DiscoverHeaderHost), path)
}
func (request *Request) MakeUrl(path string) string {
return MakeUrl(request.Request, path)
}
func (response *Response) Header() http.Header {
//if response.headerWritten {
// return nil
//}
response.changed = true
if response.ProxyHeader != nil {
return *response.ProxyHeader
}
return response.Writer.Header()
}
func (response *Response) Write(bytes []byte) (int, error) {
response.checkWriteHeader()
response.changed = true
response.outLen += len(bytes)
if response.ProxyHeader != nil {
response.copyProxyHeader()
}
return response.Writer.Write(bytes)
}
func (response *Response) WriteString(s string) (int, error) {
return response.Write([]byte(s))
}
func (response *Response) WriteHeader(code int) {
response.changed = true
response.status = code
if response.ProxyHeader != nil && (response.status == 502 || response.status == 503 || response.status == 504) {
return
}
if response.ProxyHeader != nil {
response.copyProxyHeader()
}
}
func (response *Response) checkWriteHeader() {
if !response.headerWritten {
response.headerWritten = true
if response.status != 200 {
response.Writer.WriteHeader(response.status)
}
return
}
}
func (response *Response) Flush() {
if flusher, ok := response.Writer.(http.Flusher); ok {
flusher.Flush()
}
}
func (response *Response) FlushString(s string) (int, error) {
n, err := response.WriteString(s)
if err == nil {
response.Flush()
}
return n, err
}
func (response *Response) copyProxyHeader() {
src := *response.ProxyHeader
dst := response.Writer.Header()
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
response.ProxyHeader = nil
}
func (response *Response) DontLog200() {
response.dontLog200 = true
}
func (response *Response) DontLogArg(arg string) {
response.dontLogArgs = append(response.dontLogArgs, arg)
}
func (response *Response) Location(location string) {
response.WriteHeader(302)
response.Header().Set("Location", location)
}
func (response *Response) SendFile(contentType, filename string) {
response.Header().Set("Content-Type", contentType)
if mf := u.ReadFileFromMemory(filename); mf != nil {
response.Write(mf.Data)
return
}
if fd, err := os.Open(filename); err == nil {
defer fd.Close()
_, _ = io.Copy(response, fd)
}
}
func (response *Response) DownloadFile(contentType, filename string, data any) {
if contentType == "" {
contentType = "application/octet-stream"
}
response.Header().Set("Content-Type", contentType)
if filename != "" {
response.Header().Set("Content-Disposition", "attachment; filename="+filename)
}
var outBytes []byte = nil
var reader io.Reader = nil
if v, ok := data.([]byte); ok {
outBytes = v
} else if v, ok := data.(string); ok {
outBytes = []byte(v)
} else if v, ok := data.(io.Reader); ok {
reader = v
} else {
outBytes = []byte(u.Json(data))
}
if outBytes != nil {
response.Header().Set("Content-Length", u.String(len(outBytes)))
response.Write(outBytes)
} else if reader != nil {
io.Copy(response, reader)
}
}
func GetDomainWithScope(request *http.Request, scope string) string {
host := request.Header.Get(standard.DiscoverHeaderHost)
if scope == "topDomain" {
//domain := strings.SplitN(host, ":", 2)[0]
domain := host
domainParts := strings.Split(domain, ".")
if len(domainParts) >= 2 {
domain = domainParts[len(domainParts)-2] + "." + domainParts[len(domainParts)-1]
}
return domain
} else {
return host
}
}
type routeHandler struct {
webRequestingNum int64
wsConns map[string]*websocket.Conn
// TODO 记录正在处理的请求数量,连接中的WS数量,在关闭服务时能优雅的结束
}
func (rh *routeHandler) Stop() {
for _, conn := range rh.wsConns {
_ = conn.Close()
}
}
func (rh *routeHandler) Wait() {
for i := 0; i < 25; i++ {
if rh.webRequestingNum == 0 && len(rh.wsConns) == 0 {
break
}
time.Sleep(time.Millisecond * 200)
}
}
func xHeader(headerName string, request *http.Request, maker func() string) string {
h := request.Header.Get(headerName)
if h == "" {
h = maker()
request.Header.Set(headerName, h)
}
return h
}
func getLogHeaders(request *http.Request) map[string]string {
// Headers,未来可以优化日志记录,最近访问过的头部信息可省略
logHeaders := make(map[string]string)
for k, v := range request.Header {
if noLogHeaders[strings.ToLower(k)] {
continue
}
if len(v) > 1 {
logHeaders[k] = strings.Join(v, ", ")
} else {
logHeaders[k] = v[0]
}
}
return logHeaders
}
func parseRequestURI(request *http.Request, args *map[string]any) {
if strings.Index(request.RequestURI, request.URL.Path) == -1 && strings.LastIndex(request.RequestURI, "?") != -1 {
requestUrl, reqErr := url.Parse(request.RequestURI)
if reqErr == nil {
queryStringArr, reqErr := url.ParseQuery(requestUrl.RawQuery)
if reqErr == nil && len(queryStringArr) > 0 {
for paramName, paramValue := range queryStringArr {
if len(paramValue) < 1 {
continue
}
if len(paramValue) > 1 {
(*args)[paramName] = paramValue
} else {
(*args)[paramName] = paramValue[0]
}
}
}
}
}
}
func parseService(request *http.Request, host, requestPath string, args *map[string]any) (*webServiceType, *websocketServiceType) {
var s *webServiceType
var ws *websocketServiceType
webServicesLock.RLock()
s = webServices[fmt.Sprint(host, request.Method, requestPath)]
//fmt.Println(111, fmt.Sprint(host, request.Method, requestPath), s)
if s == nil {
//fmt.Println(222, fmt.Sprint(host, requestPath), s)
s = webServices[fmt.Sprint(host, requestPath)]
if s == nil {
port := ":80"
if request.TLS != nil {
port = ":443"
}
if strings.ContainsRune(host, ':') {
port = ":" + strings.SplitN(host, ":", 2)[1]
}
//fmt.Println(333, fmt.Sprint(port, request.Method, requestPath), s)
s = webServices[fmt.Sprint(port, request.Method, requestPath)]
if s == nil {
//fmt.Println(444, fmt.Sprint(request.Method, requestPath), s)
s = webServices[fmt.Sprint(request.Method, requestPath)]
if s == nil {
s = webServices[requestPath]
}
}
}
}
webServicesLock.RUnlock()
if s == nil {
websocketServicesLock.RLock()
ws = websocketServices[fmt.Sprint(host, requestPath)]
if ws == nil {
ws = websocketServices[requestPath]
}
websocketServicesLock.RUnlock()
}
// 未匹配到缓存,尝试匹配新的 Service
if s == nil && ws == nil {
//for _, tmpS := range regexWebServices {
maxRegexWebServicesKey := len(regexWebServices) - 1
for i := maxRegexWebServicesKey; i >= 0; i-- {
tmpS := regexWebServices[i]
if tmpS.method != "" && tmpS.method != request.Method {
continue
}
if tmpS.options.Host != "" && tmpS.options.Host != request.Host {
if tmpS.options.Host[0] == ':' {
// 判断是否匹配端口
optionHostPort := "80"
if request.TLS != nil {
optionHostPort = "443"
}
if strings.Contains(request.Host, ":") {
optionHostPort = strings.SplitN(request.Host, ":", 2)[1]
}
requestHostPort := tmpS.options.Host[1:]
if optionHostPort != requestHostPort {
continue
}
} else {
continue
}
}
finds := tmpS.pathMatcher.FindAllStringSubmatch(requestPath, 20)
if len(finds) > 0 {
foundArgs := finds[0]
for i := 1; i < len(foundArgs); i++ {
unescaped, err := url.QueryUnescape(foundArgs[i])
if err == nil {
(*args)[tmpS.pathArgs[i-1]] = unescaped
} else {
(*args)[tmpS.pathArgs[i-1]] = foundArgs[i]
}
s = tmpS
}
break
}
}
}
// 未匹配到缓存和Service,尝试匹配新的WebsocketService
if s == nil && ws == nil {
//for _, tmpS := range regexWebsocketServices {
for i := len(regexWebsocketServices) - 1; i >= 0; i-- {
tmpS := regexWebsocketServices[i]
if tmpS.options.Host != "" && tmpS.options.Host != request.Host {
if tmpS.options.Host[0] == ':' {
// 判断是否匹配端口
optionHostPort := "80"
if request.TLS != nil {
optionHostPort = "443"
}
if strings.Contains(request.Host, ":") {
optionHostPort = strings.SplitN(request.Host, ":", 2)[1]
}
requestHostPort := tmpS.options.Host[1:]
if optionHostPort != requestHostPort {
continue
}
} else {
continue
}
}
finds := tmpS.pathMatcher.FindAllStringSubmatch(requestPath, 20)
if len(finds) > 0 {
foundArgs := finds[0]
for i := 1; i < len(foundArgs); i++ {
(*args)[tmpS.pathArgs[i-1]] = foundArgs[i]
ws = tmpS
}
break
}
}
}
return s, ws
}
func (rh *routeHandler) ServeHTTP(writer http.ResponseWriter, httpRequest *http.Request) {
startTime := time.Now()
var tc *TimeCounter
if Config.StatisticTime {
tc = StartTimeCounter()
defer func() {
timeStatistic.Push(tc)
//log.DefaultLogger.Info("time count", "request", request.RequestURI, "count", tc.Sprint())
}()
}
var request = &Request{Request: httpRequest, contextValues: map[string]any{}}
var response = &Response{Writer: writer, status: 200}
defer response.checkWriteHeader()
var sessionObject any = nil
headerSetSessionId := ""
headerSetDeviceId := ""
requestId := ""
host := ""
//var logHeaders map[string]string
if !Config.Fast {
// 在没有 X-Request-ID 的情况下忽略 X-Real-IP
if request.Header.Get(standard.DiscoverHeaderRequestId) == "" && !Config.AcceptXRealIpWithoutRequestId {
request.Header.Del(standard.DiscoverHeaderClientIp)
}
// 产生 X-Request-ID
requestId = xHeader(standard.DiscoverHeaderRequestId, request.Request, UniqueId)
// 真实的用户IP,通过 X-Real-IP 续传
xHeader(standard.DiscoverHeaderClientIp, request.Request, func() string {
return request.RemoteAddr[0:strings.IndexByte(request.RemoteAddr, ':')]
})
// 真实用户请求的Host,通过 X-Host 续传
host = xHeader(standard.DiscoverHeaderHost, request.Request, func() string {
return request.Host
})
// 真实用户请求的Scheme,通过 X-Scheme 续传
xHeader(standard.DiscoverHeaderScheme, request.Request, func() string {
return u.StringIf(request.TLS == nil, "http", "https")
})
// UA
xHeader(standard.DiscoverHeaderUserAgent, request.Request, func() string {
return request.Header.Get("User-Agent")
})
// SessionId
if usedSessionIdKey != "" {
// 优先从 Header 中读取
// sessionId := GetSessionId(request, response)
sessionId := request.Header.Get(usedSessionIdKey)
if sessionId == "" && !Config.SessionWithoutCookie {
if ck, err := request.Cookie(usedSessionIdKey); err == nil {
sessionId = ck.Value
if sessionId != "" {
headerSetSessionId = sessionId
}
}
}
if sessionId == "" {
sessionId = request.Header.Get(standard.DiscoverHeaderSessionId)
}
if sessionId == "" {
// 自动生成 SessionId
if sessionIdMaker != nil {
sessionId = sessionIdMaker()
} else {
sessionId = UniqueId20()
}
if !Config.SessionWithoutCookie {
cookie := http.Cookie{
Name: usedSessionIdKey,
Value: sessionId,
Path: "/",
HttpOnly: true,
}
if Config.CookieScope != "host" {
cookie.Domain = GetDomainWithScope(request.Request, Config.CookieScope)
}
http.SetCookie(response, &cookie)
}
headerSetSessionId = sessionId
// response.Header().Set(usedSessionIdKey, sessionId)
}
// 为了在服务间调用时续传 SessionId
request.Header.Set(standard.DiscoverHeaderSessionId, sessionId)
}
// DeviceId
if usedDeviceIdKey != "" {
// 优先从 Header 中读取
deviceId := request.Header.Get(usedDeviceIdKey)
if deviceId == "" && !Config.SessionWithoutCookie {
// 尝试从 Cookie 中读取
if cookie, err := request.Cookie(usedDeviceIdKey); err == nil {
deviceId = cookie.Value
if deviceId != "" {
headerSetDeviceId = deviceId
}
}
}
if deviceId == "" {
deviceId = request.Header.Get(standard.DiscoverHeaderDeviceId)
}
if deviceId == "" {
// 自动生成 DeviceId
deviceId = UniqueId20()
if !Config.SessionWithoutCookie {
cookie := http.Cookie{
Name: usedDeviceIdKey,
Value: deviceId,
Path: "/",
Expires: time.Now().AddDate(10, 0, 0),
HttpOnly: true,
}
if Config.CookieScope != "host" {
cookie.Domain = GetDomainWithScope(request.Request, Config.CookieScope)
}
http.SetCookie(response, &cookie)
}
headerSetDeviceId = deviceId
// response.Header().Set(usedDeviceIdKey, deviceId)
}
// 为了在服务间调用时续传 DeviceId
request.Header.Set(standard.DiscoverHeaderDeviceId, deviceId)
}
// ClientAppName、ClientAppVersion
if usedClientAppKey != "" {
// 为了在服务间调用时续传 ClientAppName、ClientAppVersion
request.Header.Set(standard.DiscoverHeaderClientAppName, request.Header.Get(usedClientAppKey+"Name"))
request.Header.Set(standard.DiscoverHeaderClientAppVersion, request.Header.Get(usedClientAppKey+"Version"))
}
//fmt.Println(u.JsonP(logHeaders))
if Config.StatisticTime {
tc.Add("Make Headers")
}
} else {
requestId = UniqueId()
host = request.Host
}
request.Id = requestId
response.Id = requestId
requestLogger := log.New(requestId)
if Config.Fast {
if Config.StatisticTime {
tc.Add("Pre")
}
}
if httpRequest.Method == "PRI" {
writer.WriteHeader(200)
writer.Header().Set("Upgrade", "h2c")
writer.Header().Set("Connection", "Upgrade")
writer.Header().Set("Content-Length", "0")
writer.Header().Set("Content-Type", "text/plain")
writeLog(requestLogger, "PRI", nil, 0, request.Request, response, nil, &startTime, 0, nil)
return
}
// 处理 Rewrite,如果是外部转发,直接结束请求
if processRewrite(request, response, &startTime, requestLogger) {
return
}
if Config.StatisticTime {
tc.Add("Check Rewrite")
}
//var requestPath string
//pos := strings.LastIndex(request.RequestURI, "?")
//if pos != -1 {
// requestPath = request.RequestURI[0:pos]
//} else {
// requestPath = request.RequestURI
//}
requestPath := request.URL.Path
// 处理静态文件
processStaticOK, staticFile := processStatic(requestPath, request, response, &startTime, requestLogger)
if processStaticOK {
return
}
if Config.StatisticTime {
tc.Add("Check Static")
}
// 处理 ProxyBy
if processProxy(request, response, &startTime, requestLogger) {
return
}
if Config.StatisticTime {
tc.Add("Check Proxy")
}
if headerSetSessionId != "" {
response.Header().Set(usedSessionIdKey, headerSetSessionId)
}
if headerSetDeviceId != "" {
response.Header().Set(usedDeviceIdKey, headerSetDeviceId)
}
args := make(map[string]any)
// 先看缓存中是否有 Service
//var s *webServiceType
//var ws *websocketServiceType
//fmt.Println(request.Host, request.Method, requestPath)
//fmt.Println(u.JsonP(webServices))
s, ws := parseService(request.Request, host, requestPath, &args)
if Config.StatisticTime {
tc.Add("Find Service")
}
// 判定是rewrite
// rewrite问号后的参数不能被request.Form解析 解析问号后的参数
parseRequestURI(request.Request, &args)
// GET POST
err := request.ParseForm()
if err != nil {
logError(err.Error())
} else {
reqForm := request.Form
for k, v := range reqForm {
if len(v) > 1 {
args[k] = v
} else {
args[k] = v[0]
}
}
}
noBody := false
noLog200 := false
if s != nil {
noBody = s.options.NoBody
noLog200 = s.options.NoLog200
} else if ws != nil {
noBody = ws.options.NoBody
noLog200 = ws.options.NoLog200
}
if noLog200 {
response.dontLog200 = true
}
// POST
if request.Body != nil && !noBody {
contentType := request.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "application/json") {
bodyBytes, _ := io.ReadAll(request.Body)
_ = request.Body.Close()
if len(bodyBytes) > 0 {
var err error
if bodyBytes[0] == 123 {
err = json.Unmarshal(bodyBytes, &args)
} else {
arg := new(any)
err = json.Unmarshal(bodyBytes, arg)
args["request"] = arg
}
if err != nil {
ServerLogger.Error(err.Error())
response.WriteHeader(400)
writeLog(requestLogger, "FAIL", nil, 0, request.Request, response, args, &startTime, 0, nil)
return
}
}
} else if strings.HasPrefix(contentType, "application/x-www-form-urlencoded") {
bodyBytes, _ := io.ReadAll(request.Body)
_ = request.Body.Close()
argsBody, err := url.ParseQuery(string(bodyBytes))
if err == nil && len(argsBody) > 0 {
for aKey, aValue := range argsBody {
aKey = strings.ReplaceAll(aKey, "[]", "")
if len(aValue) > 1 {
args[aKey] = aValue
} else {
args[aKey] = aValue[0]
}
}
}
} else if strings.HasPrefix(contentType, "multipart/form-data") {
err := request.ParseMultipartForm(Config.MaxUploadSize)
if err == nil {
defer request.MultipartForm.RemoveAll()
for aKey, aValue := range request.MultipartForm.Value {
aKey = strings.ReplaceAll(aKey, "[]", "")
if len(aValue) > 1 {
args[aKey] = aValue
} else if len(aValue) == 1 {
args[aKey] = aValue[0]
}
}
for aKey, aValue := range request.MultipartForm.File {
aKey = strings.ReplaceAll(aKey, "[]", "")
uploads := make([]UploadFile, len(aValue))
for i := len(aValue) - 1; i >= 0; i-- {
fileHeader := aValue[i]
uploads[i] = UploadFile{
fileHeader: fileHeader,
Filename: fileHeader.Filename,
Header: fileHeader.Header,
Size: fileHeader.Size,
}
}
if len(aValue) > 1 {
args[aKey] = uploads
} else if len(aValue) == 1 {
args[aKey] = uploads[0]
}
}
}
}
}
if Config.StatisticTime {
tc.Add("Make Args")
}
// 前置过滤器
var result any = nil
prevRequestURI := request.RequestURI
for _, filter := range inFilters {
result = filter(&args, request, response, requestLogger)
if result != nil {
break
}
}
// 重定向
if prevRequestURI != request.RequestURI {
requestPath = request.URL.Path
s, ws = parseService(request.Request, host, requestPath, &args)
parseRequestURI(request.Request, &args)
}
if Config.StatisticTime {
tc.Add("In Filter")
}
var authLevel = 0
var options *WebServiceOptions
if ws != nil {
authLevel = ws.authLevel
} else if s != nil {
options = &s.options
authLevel = s.authLevel
}
defer func() {
if err := recover(); err != nil {
var out any
if errorHandle != nil {
out = errorHandle(err, request, response)
} else {
response.WriteHeader(ResponseCodePanicError)
out = ""
}
logError(u.String(err))
writeLog(requestLogger, "PANIC", out, response.outLen, request.Request, response, args, &startTime, authLevel, Map{
"error": u.String(err),
})
}
//if sessionObjects[request] != nil {
// delete(sessionObjects, request)
//}
}()
// 全都未匹配,输出404(在前置过滤器之后再判断404)
if s == nil && ws == nil {
response.WriteHeader(404)
if requestPath != "/favicon.ico" {
writeLog(requestLogger, "FAIL", nil, 0, request.Request, response, args, &startTime, 0, Map{
"file": staticFile,
})
}
return
}
if result == nil {
// 之前未产生结果,进行验证
ac := webAuthCheckers[authLevel]
if ac == nil {
ac = webAuthChecker
}
pass, object := ac(authLevel, requestLogger, &request.RequestURI, args, request, response, options)
if pass == false {
//usedTime := float32(time.Now().UnixNano()-startTime.UnixNano()) / 1e6
//byteArgs, _ := json.Marshal(args)
//byteHeaders, _ := json.Marshal(logHeaders)
//log.Printf("REJECT %s %s %s %s %.6f %s %s %d %s", request.RemoteAddr, request.Host, request.Method, request.RequestURI, usedTime, string(byteArgs), string(byteHeaders), authLevel, request.Proto)
response.WriteHeader(403)
if object == nil && webAuthFailedData != nil {
object = webAuthFailedData
}
if object == nil {
outLen := 0
if !response.changed {
response.checkWriteHeader()
} else {
outLen = response.outLen
}
writeLog(requestLogger, "REJECT", result, outLen, request.Request, response, args, &startTime, authLevel, nil)
} else {
var outData any
var outLen int
outBytes, outContentType := makeOutput(object)
if outContentType != "" {
response.Header().Set("Content-Type", outContentType)
}
n, err := response.Write(outBytes)
if err != nil {
logError(err.Error(), "wrote", n)
}
outData = object
outLen = len(outBytes)
writeLog(requestLogger, "ACCESS", outData, outLen, request.Request, response, args, &startTime, authLevel, nil)
}
return
} else {
sessionObject = object
}
}
if Config.StatisticTime {
tc.Add("Auth Check")
}
// 处理 Proxy
//var logName string
//var statusCode int
//if proxyToApp != nil {
// caller := &Caller{request: request}
// r := caller.Do(request.Method, *proxyToApp, *proxyToPath, args, "Host", request.Host)
// result = r.Bytes()
// statusCode = 500
// if r.Error == nil && r.Response != nil {
// statusCode = r.Response.StatusCode
// }
// logName = "PROXY"
//} else {
// 处理 Websocket
if ws != nil && result == nil {
doWebsocketService(ws, request, response, authLevel, args, &startTime, requestLogger, sessionObject)
} else if s != nil || result != nil {
result = doWebService(s, request, response, args, result, requestLogger, sessionObject)
//logName = "ACCESS"
//statusCode = 200
}
//}
if Config.StatisticTime {
tc.Add("Do Request")
}
if response.dontLogArgs != nil && len(response.dontLogArgs) > 0 {
for _, arg := range response.dontLogArgs {
delete(args, arg)
}
}
if ws == nil {
// 后置过滤器
for _, filter := range outFilters {
newResult, done := filter(args, request, response, result, requestLogger)
if newResult != nil {
result = newResult
}
if done {
break
}
}
if Config.StatisticTime {
tc.Add("Out Filter")
}
// 返回结果
outBytes, outContentType := makeOutput(result)
if outContentType != "" {
response.Header().Set("Content-Type", outContentType)
}
isZipOuted := false
if Config.Compress && len(outBytes) >= Config.CompressMinSize && len(outBytes) <= Config.CompressMaxSize && strings.Contains(request.Header.Get("Accept-Encoding"), "gzip") {
zipWriter, err := gzip.NewWriterLevel(response, 1)
if err == nil {
response.Header().Set("Content-Encoding", "gzip")
n, err := zipWriter.Write(outBytes)
if err != nil {
logError(err.Error(), "wrote", n)
} else {
isZipOuted = true
}
_ = zipWriter.Close()
}
}