-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathfiber.context.go
More file actions
869 lines (735 loc) · 26.6 KB
/
fiber.context.go
File metadata and controls
869 lines (735 loc) · 26.6 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
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
package evo
import (
"bufio"
"context"
"encoding/base64"
"encoding/xml"
"errors"
"fmt"
"github.com/getevo/evo/v2/lib/frm"
"github.com/getevo/evo/v2/lib/generic"
"github.com/getevo/evo/v2/lib/outcome"
"github.com/getevo/json"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/utils/v2"
"github.com/tidwall/gjson"
"github.com/valyala/fasthttp"
"io"
"mime"
"mime/multipart"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
// Accepts checks if the specified extensions or content types are acceptable.
func (r *Request) Accepts(offers ...string) (offer string) {
return r.Context.Accepts(offers...)
}
// AcceptsCharsets checks if the specified charset is acceptable.
func (r *Request) AcceptsCharsets(offers ...string) (offer string) {
return r.Context.AcceptsCharsets(offers...)
}
// AcceptsEncodings checks if the specified encoding is acceptable.
func (r *Request) AcceptsEncodings(offers ...string) (offer string) {
return r.Context.AcceptsEncodings(offers...)
}
// AcceptsLanguages checks if the specified language is acceptable.
func (r *Request) AcceptsLanguages(offers ...string) (offer string) {
return r.Context.AcceptsLanguages(offers...)
}
// AppendHeader the specified value to the HTTP response header field.
// If the header is not already set, it creates the header with the specified value.
func (r *Request) AppendHeader(field string, values ...string) {
r.Context.Append(field, values...)
}
// Attachment sets the HTTP response Content-Disposition header field to attachment.
func (r *Request) Attachment(name ...string) {
r.Context.Attachment(name...)
}
// QueryString returns url query string.
func (r *Request) QueryString() string {
return r.URL().QueryString
}
// BaseURL returns (protocol + host).
func (r *Request) BaseURL() string {
return r.Context.BaseURL()
}
// Body contains the raw body submitted in a POST request.
func (r *Request) Body() string {
return string(r.Context.Body())
}
// BodyParser binds the request body to a struct.
// It supports decoding the following content types based on the Content-Type header:
// application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data
func (r *Request) BodyParser(out any) error {
ctype := r.ContentType()
if strings.HasPrefix(ctype, MIMEApplicationJSON) {
return json.Unmarshal(r.Context.Request().Body(), out)
} else if strings.HasPrefix(ctype, MIMETextXML) || strings.HasPrefix(ctype, MIMEApplicationXML) {
return xml.Unmarshal(r.Context.Request().Body(), out)
} else if strings.HasPrefix(ctype, MIMEApplicationForm) || strings.HasPrefix(ctype, MIMEMultipartForm) {
dec := frm.NewDecoder(&frm.DecoderOptions{
TagName: "json",
IgnoreUnknownKeys: true,
})
var data, err = r.Form()
if err != nil {
return err
}
return dec.Decode(data, out)
}
return fmt.Errorf("undefined body type")
//return r.Context.BodyParser(out)
}
// ContentType returns request content type
func (r *Request) ContentType() string {
return string(r.Context.Request().Header.ContentType())
}
// UserAgent returns request useragent
func (r *Request) UserAgent() string {
ua := r.Header("User-Agent")
if ua == "" {
ua = r.Header("X-Original-Agent")
}
if ua == "" {
ua = r.Header("X-User-Agent")
}
return ua
}
// IP returns user ip
func (r *Request) IP() string {
if fiberConfig.ServerHeader != "" {
return r.Header(fiberConfig.ServerHeader)
}
return r.Context.IP()
}
// ClearCookie expires a specific cookie by key.
// If no key is provided it expires all cookies.
func (r *Request) ClearCookie(key ...string) {
r.Context.ClearCookie(key...)
}
// SetRawCookie sets a cookie by passing a cookie struct
func (r *Request) SetRawCookie(cookie *outcome.Cookie) {
fcookie := fasthttp.AcquireCookie()
fcookie.SetKey(cookie.Name)
fcookie.SetValue(cookie.Value)
fcookie.SetPath(cookie.Path)
fcookie.SetDomain(cookie.Domain)
fcookie.SetExpire(cookie.Expires)
fcookie.SetSecure(cookie.Secure)
fcookie.SetHTTPOnly(cookie.HTTPOnly)
switch utils.ToLower(cookie.SameSite) {
case "strict":
fcookie.SetSameSite(fasthttp.CookieSameSiteStrictMode)
case "none":
fcookie.SetSameSite(fasthttp.CookieSameSiteNoneMode)
default:
fcookie.SetSameSite(fasthttp.CookieSameSiteLaxMode)
}
r.Context.Response().Header.SetCookie(fcookie)
fasthttp.ReleaseCookie(fcookie)
}
// Cookie is used for getting a cookie value by key
func (r *Request) Cookie(key string) (value string) {
return r.Context.Cookies(key)
}
// Download transfers the file from path as an attachment.
// Typically, browsers will prompt the user for download.
// By default, the Content-Disposition header filename= parameter is the filepath (this typically appears in the browser dialog).
// Override this default with the filename parameter.
func (r *Request) Download(file string, name ...string) error {
return r.Context.Download(file, name...)
}
// Format performs content-negotiation on the Accept HTTP header.
// It uses Accepts to select a proper format.
// If the header is not specified or there is no proper format, text/plain is used.
func (r *Request) Format(body any) error {
var b string
accept := r.Context.Accepts("html", "json")
switch val := body.(type) {
case string:
b = val
case []byte:
b = string(val)
default:
b = fmt.Sprintf("%+v", val)
}
switch accept {
case "html":
return r.Context.SendString(b)
case "json":
if err := r.Context.JSON(body); err != nil {
return err
}
default:
return r.Context.SendString(b)
}
return nil
}
// FormFile returns the first file by key from a MultipartForm.
func (r *Request) FormFile(key string) (*multipart.FileHeader, error) {
return r.Context.FormFile(key)
}
// ParseJsonBody returns parsed JSON Body using gjson.
func (r *Request) ParseJsonBody() *gjson.Result {
if r.jsonParsedBody == nil {
var t = gjson.Parse(string(r.Context.Body()))
r.jsonParsedBody = &t
}
return r.jsonParsedBody
}
// BodyValue returns the first value by key from a MultipartForm or JSON Body.
func (r *Request) BodyValue(key string) generic.Value {
ctype := r.ContentType()
if strings.HasPrefix(ctype, MIMEApplicationJSON) {
if r.jsonParsedBody == nil {
var t = gjson.Parse(string(r.Context.Body()))
r.jsonParsedBody = &t
}
return generic.Parse(r.jsonParsedBody.Get(key).String())
} else if strings.HasPrefix(ctype, MIMEApplicationForm) || strings.HasPrefix(ctype, MIMEMultipartForm) {
return r.FormValue(key)
}
return generic.Parse(nil)
}
// FormValue returns the first value by key from a MultipartForm.
func (r *Request) FormValue(key string) generic.Value {
return generic.Parse(r.Context.FormValue(key))
}
// Form.
func (r *Request) Form() (url.Values, error) {
var err error
var form url.Values
if r.Method() == "POST" || r.Method() == "PUT" || r.Method() == "PATCH" {
form, err = parsePostForm(r)
}
if form == nil {
form = url.Values{}
}
return form, err
}
func parsePostForm(r *Request) (vs url.Values, err error) {
if len(r.Body()) == 0 {
err = errors.New("missing form body")
return
}
ct := r.ContentType()
// RFC 7231, section 3.1.1.5 - empty type
// MAY be treated as application/octet-stream
if ct == "" {
ct = "application/octet-stream"
}
ct, _, err = mime.ParseMediaType(ct)
switch {
case strings.HasPrefix(ct, "application/x-www-form-urlencoded"):
return url.ParseQuery(string(r.Body()))
case strings.HasPrefix(ct, "multipart/form-data"):
v, err := r.MultipartForm()
return url.Values(v.Value), err
}
return nil, fmt.Errorf("invalid content type")
}
// Fresh not implemented yet
func (r *Request) Fresh() bool {
return r.Context.Fresh()
}
// Get returns the HTTP request header specified by field.
// Field names are case-insensitive
func (r *Request) Get(key string) generic.Value {
// It doesn't return POST'ed arguments - use PostArgs() for this.
//
// See also PostArgs, FormValue and FormFile.
if r.Context.Request().URI().QueryArgs().Has(key) {
return r.Query(key)
}
if len(r.Context.Request().Header.Peek(key)) > 0 {
return generic.Parse(r.Header(key))
}
var val = r.Header(key)
if len(val) > 0 {
return generic.Parse(val)
}
ctype := utils.ToLower(string(r.Context.Request().Header.ContentType()))
ctype = utils.ParseVendorSpecificContentType(ctype)
if strings.HasPrefix(ctype, MIMEApplicationForm) {
val = r.Context.FormValue(key)
if len(val) > 0 {
return generic.Parse(val)
}
} else if strings.HasPrefix(ctype, MIMEApplicationJSON) {
if r.jsonParsedBody == nil {
var t = gjson.Parse(string(r.Context.Body()))
r.jsonParsedBody = &t
}
return generic.Parse(r.jsonParsedBody.Get(key).String())
}
return generic.Parse(nil)
}
// Hostname contains the hostname derived from the Host HTTP header.
func (r *Request) Hostname() string {
if r.Header("X-Forwarded-Host") != "" {
return r.Header("X-Forwarded-Host")
}
if r.Header("X-Forwarded-Server") != "" {
return r.Header("X-Forwarded-Server")
}
return r.Context.Hostname()
}
// IPs returns an string slice of IP addresses specified in the X-Forwarded-For request header.
func (r *Request) IPs() []string {
if len(r.Context.IPs()) > 0 {
return r.Context.IPs()
}
return []string{}
}
func (r *Request) Header(key string) string {
return r.Context.Get(key)
}
func (r *Request) RespHeaders() map[string]string {
var headers = map[string]string{}
var t = r.Context.GetRespHeaders()
for k, _ := range t {
headers[k] = t[k][0]
}
return headers
}
func (r *Request) ReqHeaders() map[string]string {
var headers = map[string]string{}
var t = r.Context.GetReqHeaders()
for k, _ := range t {
headers[k] = t[k][0]
}
return headers
}
func (r *Request) SetHeader(key, val string) {
r.Set(key, val)
}
// Is returns the matching content type,
// if the incoming request’s Content-Type HTTP header field matches the MIME type specified by the type parameter
func (r *Request) Is(extension string) (match bool) {
return r.Context.Is(extension)
}
// JSON converts any interface or string to JSON using Jsoniter.
// This method also sets the content header to application/json.
func (r *Request) JSON(data any) error {
raw, err := json.Marshal(data)
// Check for errors
if err != nil {
return err
}
// Set http headers
r.Context.Response().Header.SetContentType(MIMEApplicationJSON)
r.Write(raw)
return nil
}
// JSONP sends a JSON response with JSONP support.
// This method is identical to JSON, except that it opts-in to JSONP callback support.
// By default, the callback name is simply callback.
func (r *Request) JSONP(json any, callback ...string) error {
return r.Context.JSONP(json, callback...)
}
// Links joins the links followed by the property to populate the response’s Link HTTP header field.
func (r *Request) Links(link ...string) {
r.Context.Links(link...)
}
// Locals makes it possible to pass any values under string keys scoped to the request
// and therefore available to all following routes that match the request.
func (r *Request) Locals(key string, value ...any) (val any) {
return r.Context.Locals(key, value...)
}
// Location sets the response Location HTTP header to the specified path parameter.
func (r *Request) Location(path string) {
r.Context.Location(path)
}
// Method contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.
func (r *Request) Method(override ...string) string {
return r.Context.Method(override...)
}
// MultipartForm parse form entries from binary.
// This returns a map[string][]string, so given a key the value will be a string slice.
func (r *Request) MultipartForm() (*multipart.Form, error) {
return r.Context.MultipartForm()
}
// Next executes the next method in the stack that matches the current route.
// You can pass an optional error for custom error handling.
func (r *Request) Next() error {
return r.Context.Next()
}
// OriginalURL contains the original request URL.
func (r *Request) OriginalURL() string {
return r.Context.OriginalURL()
}
// Param is used to get the route parameters.
// Defaults to empty string "", if the param doesn't exist.
func (r *Request) Param(key string) generic.Value {
return generic.Parse(r.Context.Params(key))
}
// Path returns the path part of the request URL.
// Optionally, you could override the path.
func (r *Request) Path(override ...string) string {
return r.Context.Path(override...)
}
// Protocol contains the request protocol string: http or https for TLS requests.
func (r *Request) Protocol() string {
return r.Context.Protocol()
}
// Query returns the query string parameter in the url.
func (r *Request) Query(key string) (value generic.Value) {
return generic.Parse(r.Context.Query(key))
}
// Redirect to the URL derived from the specified path, with specified status.
// If status is not specified, status defaults to 302 Found
func (r *Request) Redirect(path string, status ...int) error {
rd := r.Context.Redirect()
if len(status) > 0 {
rd = rd.Status(status[0])
}
return rd.To(path)
}
// SaveFile saves any multipart file to disk.
func (r *Request) SaveFile(fileheader *multipart.FileHeader, path string) error {
return r.Context.SaveFile(fileheader, path)
}
// IsSecure returns a boolean property, that is true, if a TLS connection is established.
func (r *Request) IsSecure() bool {
return r.Context.Secure()
}
// Send sets the HTML response body. The Send body can be of any type.
func (r *Request) SendHTML(body any) {
r.Set("Content-Type", "text/html")
r.Write(body)
}
// Send sets the HTTP response body. The Send body can be of any type.
func (r *Request) Send(body string) error {
return r.Context.Send([]byte(body))
}
// SendBytes sets the HTTP response body for []byte types
// This means no type assertion, recommended for faster performance
func (r *Request) SendBytes(body []byte) error {
return r.Context.Send(body)
}
// SendFile transfers the file from the given path.
// Sets the Content-Type response HTTP header field based on the filenames extension.
func (r *Request) SendFile(file string, cfg ...fiber.SendFile) error {
return r.Context.SendFile(file, cfg...)
}
// SendStatus sets the HTTP status code and if the response body is empty,
// it sets the correct status message in the body.
func (r *Request) SendStatus(status int) error {
return r.Context.SendStatus(status)
}
// SendString sets the HTTP response body for string types
// This means no type assertion, recommended for faster performance
func (r *Request) SendString(body string) error {
return r.Context.SendString(body)
}
// Set sets the response’s HTTP header field to the specified key, value.
func (r *Request) Set(key string, val string) {
r.Context.Set(key, val)
}
// Subdomains returns a string slive of subdomains in the domain name of the request.
// The subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.
func (r *Request) Subdomains(offset ...int) []string {
return r.Context.Subdomains(offset...)
}
// Stale is not implemented yet, pull requests are welcome!
func (r *Request) Stale() bool {
return r.Context.Stale()
}
// Status sets the HTTP status for the response.
// This method is chainable.
func (r *Request) Status(status int) *Request {
r.Context.Status(status)
return r
}
// Type sets the Content-Type HTTP header to the MIME type specified by the file extension.
func (r *Request) Type(ext string) *Request {
r.Context.Type(ext)
return r
}
// Vary adds the given header field to the Vary response header.
// This will append the header, if not already listed, otherwise leaves it listed in the current location.
func (r *Request) Vary(fields ...string) {
r.Context.Vary(fields...)
}
// Write appends any input to the HTTP body response.
func (r *Request) Write(body any) {
var data []byte
switch body := body.(type) {
case string:
data = []byte(body)
case []byte:
data = body
case int:
data = []byte(strconv.Itoa(body))
case bool:
data = []byte(strconv.FormatBool(body))
case io.Reader:
r.Context.Response().SetBodyStream(body, -1)
return
default:
data = []byte(fmt.Sprintf("%v", body))
}
if r.status > 0 {
r.Status(r.status)
}
if r.beforeResponse != nil {
r.beforeResponse(data)
}
r.Context.Response().SetBody(data)
}
// XHR returns a Boolean property, that is true, if the request’s X-Requested-With header field is XMLHttpRequest,
// indicating that the request was issued by a client library (such as jQuery).
func (r *Request) XHR() bool {
return r.Context.XHR()
}
// SetCookie set cookie with given name,value and optional params (wise function)
func (r *Request) SetCookie(key string, val any, params ...any) {
cookie := new(outcome.Cookie)
cookie.Name = key
cookie.Path = "/"
ref := reflect.ValueOf(val)
switch ref.Kind() {
case reflect.String:
cookie.Value = val.(string)
break
case reflect.Ptr:
r.SetCookie(key, ref.Elem().Interface(), params...)
return
case reflect.Map, reflect.Struct, reflect.Array, reflect.Slice:
b, _ := json.Marshal(val)
cookie.Value = base64.RawStdEncoding.EncodeToString(b)
break
default:
cookie.Value = fmt.Sprint(val)
}
for _, item := range params {
if v, ok := item.(time.Duration); ok {
cookie.Expires = time.Now().Add(v)
}
if v, ok := item.(time.Time); ok {
cookie.Expires = v
}
}
r.SetRawCookie(cookie)
}
// Params return map of parameters in url
func (r *Request) Params() map[string]string {
result := make(map[string]string)
for _, key := range r.Context.Route().Params {
result[key] = r.Context.Params(key)
}
return result
}
// Route generate route for named routes
func (r *Request) Route(name string, params ...any) string {
var m = fiber.Map{}
var jump = false
var route = app.GetRoute(name)
if len(route.Params) == len(params) {
for idx, key := range route.Params {
m[key] = params[idx]
}
} else if 2*len(route.Params) == len(params) {
for idx, param := range params {
if jump {
jump = false
continue
}
switch p := param.(type) {
case string:
if len(params) > idx+1 {
m[p] = params[idx+1]
jump = true
}
case map[string]any:
m = p
}
}
}
var url, _ = r.Context.GetRouteURL(name, m)
return url
}
func (r *Request) Break() {
r._break = true
}
// --- Fiber v3 additions ---
// BodyRaw returns the raw (undecoded) request body bytes.
// Unlike Body(), this skips decompression.
func (r *Request) BodyRaw() []byte {
return r.Context.BodyRaw()
}
// Queries returns all query parameters as a flat map[string]string.
func (r *Request) Queries() map[string]string {
return r.Context.Queries()
}
// FullURL returns the full request URL (protocol + host + path + query).
func (r *Request) FullURL() string {
return r.Context.FullURL()
}
// HasBody returns true if the request declares a body via Content-Length,
// Transfer-Encoding, or already-buffered payload data.
func (r *Request) HasBody() bool {
return r.Context.HasBody()
}
// HasHeader reports whether the request includes a header with the given key.
func (r *Request) HasHeader(key string) bool {
return r.Context.HasHeader(key)
}
// IsFromLocal returns true if the request originated from localhost.
func (r *Request) IsFromLocal() bool {
return r.Context.IsFromLocal()
}
// Drop closes the underlying connection without sending any response headers
// or body. Useful for DDoS mitigation.
func (r *Request) Drop() error {
return r.Context.Drop()
}
// Port returns the remote port of the request.
func (r *Request) Port() string {
return r.Context.Port()
}
// Referer returns the value of the Referer request header.
func (r *Request) Referer() string {
return r.Context.Referer()
}
// MediaType returns the MIME type from the Content-Type header without parameters.
func (r *Request) MediaType() string {
return r.Context.MediaType()
}
// Charset returns the charset parameter from the Content-Type header.
func (r *Request) Charset() string {
return r.Context.Charset()
}
// Bind returns the Fiber v3 Bind helper for unified request binding.
// Use it to bind body, query, headers, cookies, URI params into structs:
//
// var body MyDTO
// if err := r.Bind().Body(&body); err != nil { ... }
// if err := r.Bind().Query(&q); err != nil { ... }
func (r *Request) Bind() *fiber.Bind {
return r.Context.Bind()
}
// XML serialises data to XML and sends it with Content-Type application/xml.
func (r *Request) XML(data any) error {
return r.Context.XML(data)
}
// AutoFormat performs content-negotiation on the Accept header and sends
// the body in the best matching format (JSON, XML, text, etc.).
func (r *Request) AutoFormat(body any) error {
return r.Context.AutoFormat(body)
}
// SendStream sets the response body to the given io.Reader stream.
// The optional size argument sets the Content-Length header.
func (r *Request) SendStream(stream io.Reader, size ...int) error {
return r.Context.SendStream(stream, size...)
}
// --- Fiber v3 — content-type / accept helpers ---
// IsJSON reports whether the request Content-Type is application/json.
func (r *Request) IsJSON() bool { return r.Context.IsJSON() }
// IsForm reports whether the request Content-Type is application/x-www-form-urlencoded.
func (r *Request) IsForm() bool { return r.Context.IsForm() }
// IsMultipart reports whether the request Content-Type is multipart/form-data.
func (r *Request) IsMultipart() bool { return r.Context.IsMultipart() }
// AcceptsJSON reports whether the Accept header allows application/json.
func (r *Request) AcceptsJSON() bool { return r.Context.AcceptsJSON() }
// AcceptsHTML reports whether the Accept header allows text/html.
func (r *Request) AcceptsHTML() bool { return r.Context.AcceptsHTML() }
// AcceptsXML reports whether the Accept header allows application/xml or text/xml.
func (r *Request) AcceptsXML() bool { return r.Context.AcceptsXML() }
// AcceptsEventStream reports whether the Accept header allows text/event-stream.
func (r *Request) AcceptsEventStream() bool { return r.Context.AcceptsEventStream() }
// AcceptLanguage returns the single best-match value from the Accept-Language header.
func (r *Request) AcceptLanguage() string { return r.Context.AcceptLanguage() }
// AcceptEncoding returns the single best-match value from the Accept-Encoding header.
func (r *Request) AcceptEncoding() string { return r.Context.AcceptEncoding() }
// AcceptsLanguagesExtended checks if any of the offered languages is acceptable
// using RFC 4647 extended filtering (subtag matching).
func (r *Request) AcceptsLanguagesExtended(offers ...string) string {
return r.Context.AcceptsLanguagesExtended(offers...)
}
// --- Fiber v3 — request metadata ---
// RequestID returns the unique request identifier from the X-Request-Id response
// header (set by Fiber's RequestID middleware) or from the incoming request header.
func (r *Request) RequestID() string { return r.Context.RequestID() }
// Host returns the raw Host header value, including the port when present.
// Use Hostname() to get only the host part without the port.
func (r *Request) Host() string { return r.Context.Host() }
// Scheme returns the request scheme: "http" or "https".
// This is an alias for Protocol().
func (r *Request) Scheme() string { return r.Context.Scheme() }
// FullPath returns the matched route pattern including any group prefixes,
// e.g. "/users/:id". Use Path() to get the actual request path.
func (r *Request) FullPath() string { return r.Context.FullPath() }
// OverrideParam overwrites the value of a named route parameter in-flight.
// Useful in middleware that rewrites routing parameters.
func (r *Request) OverrideParam(name, value string) { r.Context.OverrideParam(name, value) }
// IsWebSocket returns true if the request contains a WebSocket upgrade handshake.
func (r *Request) IsWebSocket() bool { return r.Context.IsWebSocket() }
// IsPreflight returns true if the request is a CORS preflight (OPTIONS with
// Origin and Access-Control-Request-Method headers).
func (r *Request) IsPreflight() bool { return r.Context.IsPreflight() }
// IsProxyTrusted reports whether the remote IP falls within the configured
// trusted proxy ranges.
func (r *Request) IsProxyTrusted() bool { return r.Context.IsProxyTrusted() }
// Range parses the Range request header for partial-content responses.
// size is the total length of the resource in bytes.
func (r *Request) Range(size int64) (fiber.Range, error) { return r.Context.Range(size) }
// SetContext replaces the request's context.Context. The new context is
// propagated to all downstream handlers for this request.
func (r *Request) SetContext(ctx context.Context) { r.Context.SetContext(ctx) }
// --- Fiber v3 — response helpers ---
// GetRespHeader returns the value of a response header that has already been set.
// An optional defaultValue is returned when the header is absent.
func (r *Request) GetRespHeader(key string, defaultValue ...string) string {
return r.Context.GetRespHeader(key, defaultValue...)
}
// SaveFileToStorage saves a multipart upload directly into a custom Storage
// backend (any type that satisfies fiber.Storage).
func (r *Request) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage fiber.Storage) error {
return r.Context.SaveFileToStorage(fileheader, path, storage)
}
// MsgPack serialises data to MessagePack binary format and sends it with
// Content-Type application/msgpack.
func (r *Request) MsgPack(data any, ctype ...string) error {
return r.Context.MsgPack(data, ctype...)
}
// CBOR serialises data to CBOR binary format and sends it with
// Content-Type application/cbor.
func (r *Request) CBOR(data any, ctype ...string) error {
return r.Context.CBOR(data, ctype...)
}
// SendEarlyHints sends an HTTP 103 Early Hints response with Link preload
// headers so that the browser can begin fetching resources before the final
// response is ready. hints is a slice of Link header values.
func (r *Request) SendEarlyHints(hints []string) error {
return r.Context.SendEarlyHints(hints)
}
// SendStreamWriter sets the response body to the output of a buffered writer
// function. The writer runs in the current goroutine; close when done.
func (r *Request) SendStreamWriter(streamWriter func(*bufio.Writer)) error {
return r.Context.SendStreamWriter(streamWriter)
}
// End signals the end of an SSE (Server-Sent Events) stream.
func (r *Request) End() error { return r.Context.End() }
// Writef appends a formatted string to the response body (fmt.Fprintf style).
func (r *Request) Writef(f string, a ...any) (int, error) { return r.Context.Writef(f, a...) }
// WriteString appends a string to the response body (io.StringWriter interface).
func (r *Request) WriteString(s string) (int, error) { return r.Context.WriteString(s) }
func (r *Request) Debug() string {
var debug strings.Builder
debug.WriteString(fmt.Sprintf("> %s %s HTTP/1.1\r\n", r.Method(), r.Path()))
debug.WriteString(fmt.Sprintf("> Host: %s\r\n", r.Hostname()))
headers := r.ReqHeaders()
for key, value := range headers {
debug.WriteString(fmt.Sprintf("> %s: %s\r\n", key, value))
}
debug.WriteString(">\r\n")
body := r.Body()
if body != "" {
debug.WriteString(fmt.Sprintf("%s\r\n", body))
}
return debug.String()
}