-
Notifications
You must be signed in to change notification settings - Fork 557
/
Copy pathcontext.go
1570 lines (1365 loc) · 48.6 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
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
/*
* Copyright 2022 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* The MIT License (MIT)
*
* Copyright (c) 2015-present Aliaksandr Valialkin, VertaMedia, Kirill Danshin, Erik Dubbelboer, FastHTTP Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file may have been modified by CloudWeGo authors. All CloudWeGo
* Modifications are Copyright 2022 CloudWeGo Authors.
*/
package app
import (
"context"
"fmt"
"io"
"mime/multipart"
"net"
"net/url"
"os"
"reflect"
"strings"
"sync"
"time"
"github.com/cloudwego/hertz/internal/bytesconv"
"github.com/cloudwego/hertz/internal/bytestr"
"github.com/cloudwego/hertz/pkg/app/server/binding"
"github.com/cloudwego/hertz/pkg/app/server/render"
"github.com/cloudwego/hertz/pkg/common/errors"
"github.com/cloudwego/hertz/pkg/common/tracer/traceinfo"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/network"
"github.com/cloudwego/hertz/pkg/protocol"
"github.com/cloudwego/hertz/pkg/protocol/consts"
rConsts "github.com/cloudwego/hertz/pkg/route/consts"
"github.com/cloudwego/hertz/pkg/route/param"
)
var zeroTCPAddr = &net.TCPAddr{
IP: net.IPv4zero,
}
type Handler interface {
ServeHTTP(c context.Context, ctx *RequestContext)
}
type ClientIP func(ctx *RequestContext) string
type ClientIPOptions struct {
RemoteIPHeaders []string
TrustedCIDRs []*net.IPNet
}
var defaultTrustedCIDRs = []*net.IPNet{
{ // 0.0.0.0/0 (IPv4)
IP: net.IP{0x0, 0x0, 0x0, 0x0},
Mask: net.IPMask{0x0, 0x0, 0x0, 0x0},
},
{ // ::/0 (IPv6)
IP: net.IP{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
Mask: net.IPMask{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
},
}
var defaultClientIPOptions = ClientIPOptions{
RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"},
TrustedCIDRs: defaultTrustedCIDRs,
}
var loopbackIP = net.ParseIP("127.0.0.1")
// ClientIPWithOption used to generate custom ClientIP function and set by engine.SetClientIPFunc
func ClientIPWithOption(opts ClientIPOptions) ClientIP {
return func(ctx *RequestContext) string {
remoteIPStr := ""
trustedProxy := false
if addr := ctx.RemoteAddr(); strings.HasPrefix(addr.Network(), "unix") {
// unix, unixgram, unixpacket is considered same as "127.0.0.1"
remoteIPStr = addr.String()
trustedProxy = isTrustedProxy(opts.TrustedCIDRs, loopbackIP)
} else {
h, _, err := net.SplitHostPort(strings.TrimSpace(addr.String()))
if err != nil {
return ""
}
remoteIPStr = h
trustedProxy = isTrustedProxy(opts.TrustedCIDRs, net.ParseIP(h))
}
if trustedProxy {
for _, headerName := range opts.RemoteIPHeaders {
ip, valid := validateHeader(opts.TrustedCIDRs, ctx.Request.Header.Get(headerName))
if valid {
return ip
}
}
}
return remoteIPStr
}
}
// isTrustedProxy will check whether the IP address is included in the trusted list according to trustedCIDRs
func isTrustedProxy(trustedCIDRs []*net.IPNet, remoteIP net.IP) bool {
if trustedCIDRs == nil || remoteIP == nil {
return false
}
for _, cidr := range trustedCIDRs {
if cidr.Contains(remoteIP) {
return true
}
}
return false
}
// validateHeader will parse X-Real-IP and X-Forwarded-For header and return the Initial client IP address or an untrusted IP address
func validateHeader(trustedCIDRs []*net.IPNet, header string) (clientIP string, valid bool) {
if header == "" {
return "", false
}
items := strings.Split(header, ",")
for i := len(items) - 1; i >= 0; i-- {
ipStr := strings.TrimSpace(items[i])
ip := net.ParseIP(ipStr)
if ip == nil {
break
}
// X-Forwarded-For is appended by proxy
// Check IPs in reverse order and stop when find untrusted proxy
if (i == 0) || (!isTrustedProxy(trustedCIDRs, ip)) {
return ipStr, true
}
}
return "", false
}
var defaultClientIP = ClientIPWithOption(defaultClientIPOptions)
// SetClientIPFunc sets ClientIP function implementation to get ClientIP.
// Deprecated: Use engine.SetClientIPFunc instead of SetClientIPFunc
func SetClientIPFunc(fn ClientIP) {
defaultClientIP = fn
}
type FormValueFunc func(*RequestContext, string) []byte
var defaultFormValue = func(ctx *RequestContext, key string) []byte {
v := ctx.QueryArgs().Peek(key)
if len(v) > 0 {
return v
}
v = ctx.PostArgs().Peek(key)
if len(v) > 0 {
return v
}
mf, err := ctx.MultipartForm()
if err == nil && mf.Value != nil {
vv := mf.Value[key]
if len(vv) > 0 {
return []byte(vv[0])
}
}
return nil
}
type RequestContext struct {
conn network.Conn
Request protocol.Request
Response protocol.Response
// Errors is a list of errors attached to all the handlers/middlewares who used this context.
Errors errors.ErrorChain
Params param.Params
handlers HandlersChain
fullPath string
index int8
HTMLRender render.HTMLRender
// This mutex protect Keys map.
mu sync.RWMutex
// Keys is a key/value pair exclusively for the context of each request.
Keys map[string]interface{}
hijackHandler HijackHandler
finishedMu sync.Mutex
// finished means the request end.
finished chan struct{}
// traceInfo defines the trace information.
traceInfo traceinfo.TraceInfo
// enableTrace defines whether enable trace.
enableTrace bool
// clientIPFunc get client ip by use custom function.
clientIPFunc ClientIP
// clientIPFunc get form value by use custom function.
formValueFunc FormValueFunc
binder binding.Binder
validator binding.StructValidator
exiled bool
}
// Exile marks this RequestContext as not to be recycled.
// Experimental features: Use with caution, it may have a slight impact on performance.
func (ctx *RequestContext) Exile() {
ctx.exiled = true
}
func (ctx *RequestContext) IsExiled() bool {
return ctx.exiled
}
// Flush is the shortcut for ctx.Response.GetHijackWriter().Flush().
// Will return nil if the response writer is not hijacked.
func (ctx *RequestContext) Flush() error {
if ctx.Response.GetHijackWriter() == nil {
return nil
}
return ctx.Response.GetHijackWriter().Flush()
}
func (ctx *RequestContext) SetClientIPFunc(f ClientIP) {
ctx.clientIPFunc = f
}
func (ctx *RequestContext) SetFormValueFunc(f FormValueFunc) {
ctx.formValueFunc = f
}
func (ctx *RequestContext) SetBinder(binder binding.Binder) {
ctx.binder = binder
}
func (ctx *RequestContext) SetValidator(validator binding.StructValidator) {
ctx.validator = validator
}
func (ctx *RequestContext) GetTraceInfo() traceinfo.TraceInfo {
return ctx.traceInfo
}
func (ctx *RequestContext) SetTraceInfo(t traceinfo.TraceInfo) {
ctx.traceInfo = t
}
func (ctx *RequestContext) IsEnableTrace() bool {
return ctx.enableTrace
}
// SetEnableTrace sets whether enable trace.
//
// NOTE: biz handler must not modify this value, otherwise, it may panic.
func (ctx *RequestContext) SetEnableTrace(enable bool) {
ctx.enableTrace = enable
}
// NewContext make a pure RequestContext without any http request/response information
//
// Set the Request filed before use it for handlers
func NewContext(maxParams uint16) *RequestContext {
v := make(param.Params, 0, maxParams)
ctx := &RequestContext{Params: v, index: -1}
return ctx
}
// Loop fn for every k/v in Keys
func (ctx *RequestContext) ForEachKey(fn func(k string, v interface{})) {
ctx.mu.RLock()
for key, val := range ctx.Keys {
fn(key, val)
}
ctx.mu.RUnlock()
}
func (ctx *RequestContext) SetConn(c network.Conn) {
ctx.conn = c
}
func (ctx *RequestContext) GetConn() network.Conn {
return ctx.conn
}
func (ctx *RequestContext) SetHijackHandler(h HijackHandler) {
ctx.hijackHandler = h
}
func (ctx *RequestContext) GetHijackHandler() HijackHandler {
return ctx.hijackHandler
}
func (ctx *RequestContext) GetReader() network.Reader {
return ctx.conn
}
func (ctx *RequestContext) GetWriter() network.Writer {
return ctx.conn
}
func (ctx *RequestContext) GetIndex() int8 {
return ctx.index
}
// SetIndex reset the handler's execution index
// Disclaimer: You can loop yourself to deal with this, use wisely.
func (ctx *RequestContext) SetIndex(index int8) {
ctx.index = index
}
type HandlerFunc func(c context.Context, ctx *RequestContext)
// HandlersChain defines a HandlerFunc array.
type HandlersChain []HandlerFunc
type HandlerNameOperator interface {
SetHandlerName(handler HandlerFunc, name string)
GetHandlerName(handler HandlerFunc) string
}
func SetHandlerNameOperator(o HandlerNameOperator) {
inbuiltHandlerNameOperator = o
}
type inbuiltHandlerNameOperatorStruct struct {
handlerNames map[uintptr]string
}
func (o *inbuiltHandlerNameOperatorStruct) SetHandlerName(handler HandlerFunc, name string) {
o.handlerNames[getFuncAddr(handler)] = name
}
func (o *inbuiltHandlerNameOperatorStruct) GetHandlerName(handler HandlerFunc) string {
return o.handlerNames[getFuncAddr(handler)]
}
type concurrentHandlerNameOperatorStruct struct {
handlerNames map[uintptr]string
lock sync.RWMutex
}
func (o *concurrentHandlerNameOperatorStruct) SetHandlerName(handler HandlerFunc, name string) {
o.lock.Lock()
defer o.lock.Unlock()
o.handlerNames[getFuncAddr(handler)] = name
}
func (o *concurrentHandlerNameOperatorStruct) GetHandlerName(handler HandlerFunc) string {
o.lock.RLock()
defer o.lock.RUnlock()
return o.handlerNames[getFuncAddr(handler)]
}
func SetConcurrentHandlerNameOperator() {
SetHandlerNameOperator(&concurrentHandlerNameOperatorStruct{handlerNames: map[uintptr]string{}})
}
func init() {
inbuiltHandlerNameOperator = &inbuiltHandlerNameOperatorStruct{handlerNames: map[uintptr]string{}}
}
var inbuiltHandlerNameOperator HandlerNameOperator
func SetHandlerName(handler HandlerFunc, name string) {
inbuiltHandlerNameOperator.SetHandlerName(handler, name)
}
func GetHandlerName(handler HandlerFunc) string {
return inbuiltHandlerNameOperator.GetHandlerName(handler)
}
func getFuncAddr(v interface{}) uintptr {
return reflect.ValueOf(reflect.ValueOf(v)).Field(1).Pointer()
}
// HijackHandler must process the hijacked connection c.
//
// If KeepHijackedConns is disabled, which is by default,
// the connection c is automatically closed after returning from HijackHandler.
//
// The connection c must not be used after returning from the handler, if KeepHijackedConns is disabled.
//
// When KeepHijackedConns enabled, hertz will not Close() the connection,
// you must do it when you need it. You must not use c in any way after calling Close().
//
// network.Connection provide two options of io: net.Conn and zero-copy read/write
type HijackHandler func(c network.Conn)
// Hijack registers the given handler for connection hijacking.
//
// The handler is called after returning from RequestHandler
// and sending http response. The current connection is passed
// to the handler. The connection is automatically closed after
// returning from the handler.
//
// The server skips calling the handler in the following cases:
//
// - 'Connection: close' header exists in either request or response.
// - Unexpected error during response writing to the connection.
//
// The server stops processing requests from hijacked connections.
//
// Server limits such as Concurrency, ReadTimeout, WriteTimeout, etc.
// aren't applied to hijacked connections.
//
// The handler must not retain references to ctx members.
//
// Arbitrary 'Connection: Upgrade' protocols may be implemented
// with HijackHandler. For instance,
//
// - WebSocket ( https://en.wikipedia.org/wiki/WebSocket )
// - HTTP/2.0 ( https://en.wikipedia.org/wiki/HTTP/2 )
func (ctx *RequestContext) Hijack(handler HijackHandler) {
ctx.hijackHandler = handler
}
// Last returns the last handler of the handler chain.
//
// Generally speaking, the last handler is the main handler.
func (c HandlersChain) Last() HandlerFunc {
if length := len(c); length > 0 {
return c[length-1]
}
return nil
}
func (ctx *RequestContext) Finished() <-chan struct{} {
ctx.finishedMu.Lock()
if ctx.finished == nil {
ctx.finished = make(chan struct{})
}
ch := ctx.finished
ctx.finishedMu.Unlock()
return ch
}
// GetRequest returns a copy of Request.
func (ctx *RequestContext) GetRequest() (dst *protocol.Request) {
dst = &protocol.Request{}
ctx.Request.CopyTo(dst)
return
}
// GetResponse returns a copy of Response.
func (ctx *RequestContext) GetResponse() (dst *protocol.Response) {
dst = &protocol.Response{}
ctx.Response.CopyTo(dst)
return
}
// Value returns the value associated with this context for key, or nil
// if no value is associated with key. Successive calls to Value with
// the same key returns the same result.
//
// In case the Key is reset after response, Value() return nil if ctx.Key is nil.
func (ctx *RequestContext) Value(key interface{}) interface{} {
// this ctx has been reset, return nil.
if ctx.Keys == nil {
return nil
}
if keyString, ok := key.(string); ok {
val, _ := ctx.Get(keyString)
return val
}
return nil
}
// Hijacked returns true after Hijack is called.
func (ctx *RequestContext) Hijacked() bool {
return ctx.hijackHandler != nil
}
// SetBodyStream sets response body stream and, optionally body size.
//
// bodyStream.Close() is called after finishing reading all body data
// if it implements io.Closer.
//
// If bodySize is >= 0, then bodySize bytes must be provided by bodyStream
// before returning io.EOF.
//
// If bodySize < 0, then bodyStream is read until io.EOF.
//
// See also SetBodyStreamWriter.
func (ctx *RequestContext) SetBodyStream(bodyStream io.Reader, bodySize int) {
ctx.Response.SetBodyStream(bodyStream, bodySize)
}
// Host returns requested host.
//
// The host is valid until returning from RequestHandler.
func (ctx *RequestContext) Host() []byte {
return ctx.URI().Host()
}
// RemoteAddr returns client address for the given request.
//
// If address is nil, it will return zeroTCPAddr.
func (ctx *RequestContext) RemoteAddr() net.Addr {
if ctx.conn == nil {
return zeroTCPAddr
}
addr := ctx.conn.RemoteAddr()
if addr == nil {
return zeroTCPAddr
}
return addr
}
// WriteString appends s to response body.
func (ctx *RequestContext) WriteString(s string) (int, error) {
ctx.Response.AppendBodyString(s)
return len(s), nil
}
// SetContentType sets response Content-Type.
func (ctx *RequestContext) SetContentType(contentType string) {
ctx.Response.Header.SetContentType(contentType)
}
// Path returns requested path.
//
// The path is valid until returning from RequestHandler.
func (ctx *RequestContext) Path() []byte {
return ctx.URI().Path()
}
// NotModified resets response and sets '304 Not Modified' response status code.
func (ctx *RequestContext) NotModified() {
ctx.Response.Reset()
ctx.SetStatusCode(consts.StatusNotModified)
}
// IfModifiedSince returns true if lastModified exceeds 'If-Modified-Since'
// value from the request header.
//
// The function returns true also 'If-Modified-Since' request header is missing.
func (ctx *RequestContext) IfModifiedSince(lastModified time.Time) bool {
ifModStr := ctx.Request.Header.PeekIfModifiedSinceBytes()
if len(ifModStr) == 0 {
return true
}
ifMod, err := bytesconv.ParseHTTPDate(ifModStr)
if err != nil {
return true
}
lastModified = lastModified.Truncate(time.Second)
return ifMod.Before(lastModified)
}
// URI returns requested uri.
//
// The uri is valid until returning from RequestHandler.
func (ctx *RequestContext) URI() *protocol.URI {
return ctx.Request.URI()
}
func (ctx *RequestContext) String(code int, format string, values ...interface{}) {
ctx.Render(code, render.String{Format: format, Data: values})
}
// FullPath returns a matched route full path. For not found routes
// returns an empty string.
//
// router.GET("/user/:id", func(c context.Context, ctx *app.RequestContext) {
// ctx.FullPath() == "/user/:id" // true
// })
func (ctx *RequestContext) FullPath() string {
return ctx.fullPath
}
func (ctx *RequestContext) SetFullPath(p string) {
ctx.fullPath = p
}
// SetStatusCode sets response status code.
func (ctx *RequestContext) SetStatusCode(statusCode int) {
ctx.Response.SetStatusCode(statusCode)
}
// Write writes p into response body.
func (ctx *RequestContext) Write(p []byte) (int, error) {
ctx.Response.AppendBody(p)
return len(p), nil
}
// File writes the specified file into the body stream in an efficient way.
func (ctx *RequestContext) File(filepath string) {
ServeFile(ctx, filepath)
}
func (ctx *RequestContext) FileFromFS(filepath string, fs *FS) {
defer func(old string) {
ctx.Request.URI().SetPath(old)
}(string(ctx.Request.URI().Path()))
ctx.Request.URI().SetPath(filepath)
fs.NewRequestHandler()(context.Background(), ctx)
}
// FileAttachment use an efficient way to write the file to body stream.
//
// When client download the file, it will rename the file as filename
func (ctx *RequestContext) FileAttachment(filepath, filename string) {
ctx.Response.Header.Set("content-disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
ServeFile(ctx, filepath)
}
// SetBodyString sets response body to the given value.
func (ctx *RequestContext) SetBodyString(body string) {
ctx.Response.SetBodyString(body)
}
// SetContentTypeBytes sets response Content-Type.
//
// It is safe modifying contentType buffer after function return.
func (ctx *RequestContext) SetContentTypeBytes(contentType []byte) {
ctx.Response.Header.SetContentTypeBytes(contentType)
}
// FormFile returns the first file for the provided form key.
func (ctx *RequestContext) FormFile(name string) (*multipart.FileHeader, error) {
return ctx.Request.FormFile(name)
}
// FormValue returns form value associated with the given key.
//
// The value is searched in the following places:
//
// - Query string.
// - POST or PUT body.
//
// There are more fine-grained methods for obtaining form values:
//
// - QueryArgs for obtaining values from query string.
// - PostArgs for obtaining values from POST or PUT body.
// - MultipartForm for obtaining values from multipart form.
// - FormFile for obtaining uploaded files.
//
// The returned value is valid until returning from RequestHandler.
// Use engine.SetCustomFormValueFunc to change action of FormValue.
func (ctx *RequestContext) FormValue(key string) []byte {
if ctx.formValueFunc != nil {
return ctx.formValueFunc(ctx, key)
}
return defaultFormValue(ctx, key)
}
func (ctx *RequestContext) multipartFormValue(key string) (string, bool) {
mf, err := ctx.MultipartForm()
if err == nil && mf.Value != nil {
vv := mf.Value[key]
if len(vv) > 0 {
return vv[0], true
}
}
return "", false
}
func (ctx *RequestContext) multipartFormValueArray(key string) ([]string, bool) {
mf, err := ctx.MultipartForm()
if err == nil && mf.Value != nil {
vv := mf.Value[key]
if len(vv) > 0 {
return vv, true
}
}
return nil, false
}
func (ctx *RequestContext) RequestBodyStream() io.Reader {
return ctx.Request.BodyStream()
}
// MultipartForm returns request's multipart form.
//
// Returns errNoMultipartForm if request's content-type
// isn't 'multipart/form-data'.
//
// All uploaded temporary files are automatically deleted after
// returning from RequestHandler. Either move or copy uploaded files
// into new place if you want retaining them.
//
// Use SaveMultipartFile function for permanently saving uploaded file.
//
// The returned form is valid until returning from RequestHandler.
//
// See also FormFile and FormValue.
func (ctx *RequestContext) MultipartForm() (*multipart.Form, error) {
return ctx.Request.MultipartForm()
}
// SaveUploadedFile uploads the form file to specific dst.
func (ctx *RequestContext) SaveUploadedFile(file *multipart.FileHeader, dst string) error {
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, src)
return err
}
// SetConnectionClose sets 'Connection: close' response header.
func (ctx *RequestContext) SetConnectionClose() {
ctx.Response.SetConnectionClose()
}
// IsGet returns true if request method is GET.
func (ctx *RequestContext) IsGet() bool {
return ctx.Request.Header.IsGet()
}
// IsHead returns true if request method is HEAD.
func (ctx *RequestContext) IsHead() bool {
return ctx.Request.Header.IsHead()
}
// IsPost returns true if request method is POST.
func (ctx *RequestContext) IsPost() bool {
return ctx.Request.Header.IsPost()
}
// Method return request method.
//
// Returned value is valid until returning from RequestHandler.
func (ctx *RequestContext) Method() []byte {
return ctx.Request.Header.Method()
}
// NotFound resets response and sets '404 Not Found' response status code.
func (ctx *RequestContext) NotFound() {
ctx.Response.Reset()
ctx.SetStatusCode(consts.StatusNotFound)
ctx.SetBodyString(consts.StatusMessage(consts.StatusNotFound))
}
func (ctx *RequestContext) redirect(uri []byte, statusCode int) {
ctx.Response.Header.SetCanonical(bytestr.StrLocation, uri)
statusCode = getRedirectStatusCode(statusCode)
ctx.Response.SetStatusCode(statusCode)
}
func getRedirectStatusCode(statusCode int) int {
if statusCode == consts.StatusMovedPermanently || statusCode == consts.StatusFound ||
statusCode == consts.StatusSeeOther || statusCode == consts.StatusTemporaryRedirect ||
statusCode == consts.StatusPermanentRedirect {
return statusCode
}
return consts.StatusFound
}
// Copy returns a copy of the current context that can be safely used outside
// the request's scope.
//
// NOTE: If you want to pass requestContext to a goroutine, call this method
// to get a copy of requestContext.
func (ctx *RequestContext) Copy() *RequestContext {
cp := &RequestContext{
conn: ctx.conn,
Params: ctx.Params,
}
ctx.Request.CopyTo(&cp.Request)
ctx.Response.CopyTo(&cp.Response)
cp.index = rConsts.AbortIndex
cp.handlers = nil
cp.Keys = map[string]interface{}{}
ctx.mu.RLock()
for k, v := range ctx.Keys {
cp.Keys[k] = v
}
ctx.mu.RUnlock()
paramCopy := make([]param.Param, len(cp.Params))
copy(paramCopy, cp.Params)
cp.Params = paramCopy
cp.fullPath = ctx.fullPath
cp.clientIPFunc = ctx.clientIPFunc
cp.formValueFunc = ctx.formValueFunc
cp.binder = ctx.binder
cp.validator = ctx.validator
return cp
}
// Next should be used only inside middleware.
// It executes the pending handlers in the chain inside the calling handler.
func (ctx *RequestContext) Next(c context.Context) {
ctx.index++
for ctx.index < int8(len(ctx.handlers)) {
ctx.handlers[ctx.index](c, ctx)
ctx.index++
}
}
// Handler returns the main handler.
func (ctx *RequestContext) Handler() HandlerFunc {
return ctx.handlers.Last()
}
// Handlers returns the handler chain.
func (ctx *RequestContext) Handlers() HandlersChain {
return ctx.handlers
}
func (ctx *RequestContext) SetHandlers(hc HandlersChain) {
ctx.handlers = hc
}
// HandlerName returns the main handler's name.
//
// For example if the handler is "handleGetUsers()", this function will return "main.handleGetUsers".
func (ctx *RequestContext) HandlerName() string {
return utils.NameOfFunction(ctx.handlers.Last())
}
func (ctx *RequestContext) ResetWithoutConn() {
ctx.Params = ctx.Params[0:0]
ctx.Errors = ctx.Errors[0:0]
ctx.handlers = nil
ctx.index = -1
ctx.fullPath = ""
ctx.Keys = nil
if ctx.finished != nil {
close(ctx.finished)
ctx.finished = nil
}
ctx.Request.ResetWithoutConn()
ctx.Response.Reset()
if ctx.IsEnableTrace() {
ctx.traceInfo.Reset()
}
}
// Reset resets requestContext.
//
// NOTE: It is an internal function. You should not use it.
func (ctx *RequestContext) Reset() {
ctx.ResetWithoutConn()
ctx.conn = nil
}
// Redirect returns an HTTP redirect to the specific location.
// Note that this will not stop the current handler.
// In other words, even if Redirect() is called, the remaining handlers will still be executed and cause unexpected result.
// So it should call Abort to ensure the remaining handlers of this request will not be called.
//
// ctx.Abort()
// return
func (ctx *RequestContext) Redirect(statusCode int, uri []byte) {
ctx.redirect(uri, statusCode)
}
// Header is an intelligent shortcut for ctx.Response.Header.Set(key, value).
// It writes a header in the response.
// If value == "", this method removes the header `ctx.Response.Header.Del(key)`.
func (ctx *RequestContext) Header(key, value string) {
if value == "" {
ctx.Response.Header.Del(key)
return
}
ctx.Response.Header.Set(key, value)
}
// Set is used to store a new key/value pair exclusively for this context.
// It also lazy initializes c.Keys if it was not used previously.
func (ctx *RequestContext) Set(key string, value interface{}) {
ctx.mu.Lock()
if ctx.Keys == nil {
ctx.Keys = make(map[string]interface{})
}
ctx.Keys[key] = value
ctx.mu.Unlock()
}
// Get returns the value for the given key, ie: (value, true).
// If the value does not exist it returns (nil, false)
func (ctx *RequestContext) Get(key string) (value interface{}, exists bool) {
ctx.mu.RLock()
value, exists = ctx.Keys[key]
ctx.mu.RUnlock()
return
}
// MustGet returns the value for the given key if it exists, otherwise it panics.
func (ctx *RequestContext) MustGet(key string) interface{} {
if value, exists := ctx.Get(key); exists {
return value
}
panic("Key \"" + key + "\" does not exist")
}
// GetString returns the value associated with the key as a string. Return "" when type is error.
func (ctx *RequestContext) GetString(key string) (s string) {
if val, ok := ctx.Get(key); ok && val != nil {
s, _ = val.(string)
}
return
}
// GetBool returns the value associated with the key as a boolean. Return false when type is error.
func (ctx *RequestContext) GetBool(key string) (b bool) {
if val, ok := ctx.Get(key); ok && val != nil {
b, _ = val.(bool)
}
return
}
// GetInt returns the value associated with the key as an integer. Return 0 when type is error.
func (ctx *RequestContext) GetInt(key string) (i int) {
if val, ok := ctx.Get(key); ok && val != nil {
i, _ = val.(int)
}
return
}
// GetInt32 returns the value associated with the key as an integer. Return int32(0) when type is error.
func (ctx *RequestContext) GetInt32(key string) (i32 int32) {
if val, ok := ctx.Get(key); ok && val != nil {
i32, _ = val.(int32)
}
return
}
// GetInt64 returns the value associated with the key as an integer. Return int64(0) when type is error.
func (ctx *RequestContext) GetInt64(key string) (i64 int64) {
if val, ok := ctx.Get(key); ok && val != nil {
i64, _ = val.(int64)
}
return
}
// GetUint returns the value associated with the key as an unsigned integer. Return uint(0) when type is error.
func (ctx *RequestContext) GetUint(key string) (ui uint) {
if val, ok := ctx.Get(key); ok && val != nil {
ui, _ = val.(uint)
}
return
}
// GetUint32 returns the value associated with the key as an unsigned integer. Return uint32(0) when type is error.
func (ctx *RequestContext) GetUint32(key string) (ui32 uint32) {
if val, ok := ctx.Get(key); ok && val != nil {
ui32, _ = val.(uint32)
}
return
}
// GetUint64 returns the value associated with the key as an unsigned integer. Return uint64(0) when type is error.
func (ctx *RequestContext) GetUint64(key string) (ui64 uint64) {
if val, ok := ctx.Get(key); ok && val != nil {
ui64, _ = val.(uint64)
}
return
}