-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
ctx.md
2170 lines (1604 loc) · 55.6 KB
/
ctx.md
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
---
id: ctx
title: 🧠 Ctx
description: >-
The Ctx interface represents the Context which hold the HTTP request and
response. It has methods for the request query string, parameters, body, HTTP
headers, and so on.
sidebar_position: 3
---
## Accepts
Checks, if the specified **extensions** or **content** **types** are acceptable.
:::info
Based on the request’s [Accept](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept) HTTP header.
:::
```go title="Signature"
func (c Ctx) Accepts(offers ...string) string
func (c Ctx) AcceptsCharsets(offers ...string) string
func (c Ctx) AcceptsEncodings(offers ...string) string
func (c Ctx) AcceptsLanguages(offers ...string) string
```
```go title="Example"
// Accept: text/html, application/json; q=0.8, text/plain; q=0.5; charset="utf-8"
app.Get("/", func(c fiber.Ctx) error {
c.Accepts("html") // "html"
c.Accepts("text/html") // "text/html"
c.Accepts("json", "text") // "json"
c.Accepts("application/json") // "application/json"
c.Accepts("text/plain", "application/json") // "application/json", due to quality
c.Accepts("image/png") // ""
c.Accepts("png") // ""
// ...
})
```
```go title="Example 2"
// Accept: text/html, text/*, application/json, */*; q=0
app.Get("/", func(c fiber.Ctx) error {
c.Accepts("text/plain", "application/json") // "application/json", due to specificity
c.Accepts("application/json", "text/html") // "text/html", due to first match
c.Accepts("image/png") // "", due to */* without q factor 0 is Not Acceptable
// ...
})
```
Media-Type parameters are supported.
```go title="Example 3"
// Accept: text/plain, application/json; version=1; foo=bar
app.Get("/", func(c fiber.Ctx) error {
// Extra parameters in the accept are ignored
c.Accepts("text/plain;format=flowed") // "text/plain;format=flowed"
// An offer must contain all parameters present in the Accept type
c.Accepts("application/json") // ""
// Parameter order and capitalization does not matter. Quotes on values are stripped.
c.Accepts(`application/json;foo="bar";VERSION=1`) // "application/json;foo="bar";VERSION=1"
})
```
```go title="Example 4"
// Accept: text/plain;format=flowed;q=0.9, text/plain
// i.e., "I prefer text/plain;format=flowed less than other forms of text/plain"
app.Get("/", func(c fiber.Ctx) error {
// Beware: the order in which offers are listed matters.
// Although the client specified they prefer not to receive format=flowed,
// the text/plain Accept matches with "text/plain;format=flowed" first, so it is returned.
c.Accepts("text/plain;format=flowed", "text/plain") // "text/plain;format=flowed"
// Here, things behave as expected:
c.Accepts("text/plain", "text/plain;format=flowed") // "text/plain"
})
```
Fiber provides similar functions for the other accept headers.
```go
// Accept-Charset: utf-8, iso-8859-1;q=0.2
// Accept-Encoding: gzip, compress;q=0.2
// Accept-Language: en;q=0.8, nl, ru
app.Get("/", func(c fiber.Ctx) error {
c.AcceptsCharsets("utf-16", "iso-8859-1")
// "iso-8859-1"
c.AcceptsEncodings("compress", "br")
// "compress"
c.AcceptsLanguages("pt", "nl", "ru")
// "nl"
// ...
})
```
## App
Returns the [\*App](ctx.md) reference so you could easily access all application settings.
```go title="Signature"
func (c Ctx) App() *App
```
```go title="Example"
app.Get("/stack", func(c fiber.Ctx) error {
return c.JSON(c.App().Stack())
})
```
## Append
Appends the specified **value** to the HTTP response header field.
:::caution
If the header is **not** already set, it creates the header with the specified value.
:::
```go title="Signature"
func (c Ctx) Append(field string, values ...string)
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
c.Append("Link", "http://google.com", "http://localhost")
// => Link: http://localhost, http://google.com
c.Append("Link", "Test")
// => Link: http://localhost, http://google.com, Test
// ...
})
```
## Attachment
Sets the HTTP response [Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header field to `attachment`.
```go title="Signature"
func (c Ctx) Attachment(filename ...string)
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
c.Attachment()
// => Content-Disposition: attachment
c.Attachment("./upload/images/logo.png")
// => Content-Disposition: attachment; filename="logo.png"
// => Content-Type: image/png
// ...
})
```
## AutoFormat
Performs content-negotiation on the [Accept](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept) HTTP header. It uses [Accepts](ctx.md#accepts) to select a proper format.
The supported content types are `text/html`, `text/plain`, `application/json`, and `application/xml`.
For more flexible content negotiation, use [Format](ctx.md#format).
:::info
If the header is **not** specified or there is **no** proper format, **text/plain** is used.
:::
```go title="Signature"
func (c Ctx) AutoFormat(body any) error
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
// Accept: text/plain
c.AutoFormat("Hello, World!")
// => Hello, World!
// Accept: text/html
c.AutoFormat("Hello, World!")
// => <p>Hello, World!</p>
type User struct {
Name string
}
user := User{"John Doe"}
// Accept: application/json
c.AutoFormat(user)
// => {"Name":"John Doe"}
// Accept: application/xml
c.AutoFormat(user)
// => <User><Name>John Doe</Name></User>
// ..
})
```
## BaseURL
Returns the base URL \(**protocol** + **host**\) as a `string`.
```go title="Signature"
func (c Ctx) BaseURL() string
```
```go title="Example"
// GET https://example.com/page#chapter-1
app.Get("/", func(c fiber.Ctx) error {
c.BaseURL() // https://example.com
// ...
})
```
## Bind
Bind is a method that support supports bindings for the request/response body, query parameters, URL parameters, cookies and much more.
It returns a pointer to the [Bind](./bind.md) struct which contains all the methods to bind the request/response data.
For detailed information check the [Bind](./bind.md) documentation.
```go title="Signature"
func (c Ctx) Bind() *Bind
```
```go title="Example"
app.Post("/", func(c fiber.Ctx) error {
user := new(User)
// Bind the request body to a struct:
return c.Bind().Body(user)
})
```
## Body
As per the header `Content-Encoding`, this method will try to perform a file decompression from the **body** bytes. In case no `Content-Encoding` header is sent, it will perform as [BodyRaw](#bodyraw).
```go title="Signature"
func (c Ctx) Body() []byte
```
```go title="Example"
// echo 'user=john' | gzip | curl -v -i --data-binary @- -H "Content-Encoding: gzip" http://localhost:8080
app.Post("/", func(c fiber.Ctx) error {
// Decompress body from POST request based on the Content-Encoding and return the raw content:
return c.Send(c.Body()) // []byte("user=john")
})
```
:::info
Returned value is only valid within the handler. Do not store any references.
Make copies or use the [**`Immutable`**](./ctx.md) setting instead. [Read more...](../#zero-allocation)
:::
## BodyRaw
Returns the raw request **body**.
```go title="Signature"
func (c Ctx) BodyRaw() []byte
```
```go title="Example"
// curl -X POST http://localhost:8080 -d user=john
app.Post("/", func(c fiber.Ctx) error {
// Get raw body from POST request:
return c.Send(c.BodyRaw()) // []byte("user=john")
})
```
:::info
Returned value is only valid within the handler. Do not store any references.
Make copies or use the [**`Immutable`**](./ctx.md) setting instead. [Read more...](../#zero-allocation)
:::
## ClearCookie
Expire a client cookie \(_or all cookies if left empty\)_
```go title="Signature"
func (c Ctx) ClearCookie(key ...string)
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
// Clears all cookies:
c.ClearCookie()
// Expire specific cookie by name:
c.ClearCookie("user")
// Expire multiple cookies by names:
c.ClearCookie("token", "session", "track_id", "version")
// ...
})
```
:::caution
Web browsers and other compliant clients will only clear the cookie if the given options are identical to those when creating the cookie, excluding expires and maxAge. ClearCookie will not set these values for you - a technique similar to the one shown below should be used to ensure your cookie is deleted.
:::
```go title="Example"
app.Get("/set", func(c fiber.Ctx) error {
c.Cookie(&fiber.Cookie{
Name: "token",
Value: "randomvalue",
Expires: time.Now().Add(24 * time.Hour),
HTTPOnly: true,
SameSite: "lax",
})
// ...
})
app.Get("/delete", func(c fiber.Ctx) error {
c.Cookie(&fiber.Cookie{
Name: "token",
// Set expiry date to the past
Expires: time.Now().Add(-(time.Hour * 2)),
HTTPOnly: true,
SameSite: "lax",
})
// ...
})
```
## ClientHelloInfo
ClientHelloInfo contains information from a ClientHello message in order to guide application logic in the GetCertificate and GetConfigForClient callbacks.
You can refer to the [ClientHelloInfo](https://golang.org/pkg/crypto/tls/#ClientHelloInfo) struct documentation for more information on the returned struct.
```go title="Signature"
func (c Ctx) ClientHelloInfo() *tls.ClientHelloInfo
```
```go title="Example"
// GET http://example.com/hello
app.Get("/hello", func(c fiber.Ctx) error {
chi := c.ClientHelloInfo()
// ...
})
```
## Context
Returns [\*fasthttp.RequestCtx](https://godoc.org/github.com/valyala/fasthttp#RequestCtx) that is compatible with the context.Context interface that requires a deadline, a cancellation signal, and other values across API boundaries.
```go title="Signature"
func (c Ctx) Context() *fasthttp.RequestCtx
```
:::info
Please read the [Fasthttp Documentation](https://pkg.go.dev/github.com/valyala/fasthttp?tab=doc) for more information.
:::
## Cookie
Set cookie
```go title="Signature"
func (c Ctx) Cookie(cookie *Cookie)
```
```go
type Cookie struct {
Name string `json:"name"` // The name of the cookie
Value string `json:"value"` // The value of the cookie
Path string `json:"path"` // Specifies a URL path which is allowed to receive the cookie
Domain string `json:"domain"` // Specifies the domain which is allowed to receive the cookie
MaxAge int `json:"max_age"` // The maximum age (in seconds) of the cookie
Expires time.Time `json:"expires"` // The expiration date of the cookie
Secure bool `json:"secure"` // Indicates that the cookie should only be transmitted over a secure HTTPS connection
HTTPOnly bool `json:"http_only"` // Indicates that the cookie is accessible only through the HTTP protocol
SameSite string `json:"same_site"` // Controls whether or not a cookie is sent with cross-site requests
Partitioned bool `json:"partitioned"` // Indicates if the cookie is stored in a partitioned cookie jar
SessionOnly bool `json:"session_only"` // Indicates if the cookie is a session-only cookie
}
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
// Create cookie
cookie := new(fiber.Cookie)
cookie.Name = "john"
cookie.Value = "doe"
cookie.Expires = time.Now().Add(24 * time.Hour)
// Set cookie
c.Cookie(cookie)
// ...
})
```
:::info
Partitioned cookies allow partitioning the cookie jar by top-level site, enhancing user privacy by preventing cookies from being shared across different sites. This feature is particularly useful in scenarios where a user interacts with embedded third-party services that should not have access to the main site's cookies. You can check out [CHIPS](https://developers.google.com/privacy-sandbox/3pcd/chips) for more information.
:::
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
// Create a new partitioned cookie
cookie := new(fiber.Cookie)
cookie.Name = "user_session"
cookie.Value = "abc123"
cookie.Partitioned = true // This cookie will be stored in a separate jar when it's embeded into another website
// Set the cookie in the response
c.Cookie(cookie)
return c.SendString("Partitioned cookie set")
})
```
## Cookies
Get cookie value by key, you could pass an optional default value that will be returned if the cookie key does not exist.
```go title="Signature"
func (c Ctx) Cookies(key string, defaultValue ...string) string
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
// Get cookie by key:
c.Cookies("name") // "john"
c.Cookies("empty", "doe") // "doe"
// ...
})
```
:::info
Returned value is only valid within the handler. Do not store any references.
Make copies or use the [**`Immutable`**](./ctx.md) setting instead. [Read more...](../#zero-allocation)
:::
## Download
Transfers the file from path as an `attachment`.
Typically, browsers will prompt the user to download. By default, the [Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header `filename=` parameter is the file path \(_this typically appears in the browser dialog_\).
Override this default with the **filename** parameter.
```go title="Signature"
func (c Ctx) Download(file string, filename ...string) error
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
return c.Download("./files/report-12345.pdf");
// => Download report-12345.pdf
return c.Download("./files/report-12345.pdf", "report.pdf");
// => Download report.pdf
})
```
## Format
Performs content-negotiation on the [Accept](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept) HTTP header. It uses [Accepts](ctx.md#accepts) to select a proper format from the supplied offers. A default handler can be provided by setting the `MediaType` to `"default"`. If no offers match and no default is provided, a 406 (Not Acceptable) response is sent. The Content-Type is automatically set when a handler is selected.
:::info
If the Accept header is **not** specified, the first handler will be used.
:::
```go title="Signature"
func (c Ctx) Format(handlers ...ResFmt) error
```
```go title="Example"
// Accept: application/json => {"command":"eat","subject":"fruit"}
// Accept: text/plain => Eat Fruit!
// Accept: application/xml => Not Acceptable
app.Get("/no-default", func(c fiber.Ctx) error {
return c.Format(
fiber.ResFmt{"application/json", func(c fiber.Ctx) error {
return c.JSON(fiber.Map{
"command": "eat",
"subject": "fruit",
})
}},
fiber.ResFmt{"text/plain", func(c fiber.Ctx) error {
return c.SendString("Eat Fruit!")
}},
)
})
// Accept: application/json => {"command":"eat","subject":"fruit"}
// Accept: text/plain => Eat Fruit!
// Accept: application/xml => Eat Fruit!
app.Get("/default", func(c fiber.Ctx) error {
textHandler := func(c fiber.Ctx) error {
return c.SendString("Eat Fruit!")
}
handlers := []fiber.ResFmt{
{"application/json", func(c fiber.Ctx) error {
return c.JSON(fiber.Map{
"command": "eat",
"subject": "fruit",
})
}},
{"text/plain", textHandler},
{"default", textHandler},
}
return c.Format(handlers...)
})
```
## FormFile
MultipartForm files can be retrieved by name, the **first** file from the given key is returned.
```go title="Signature"
func (c Ctx) FormFile(key string) (*multipart.FileHeader, error)
```
```go title="Example"
app.Post("/", func(c fiber.Ctx) error {
// Get first file from form field "document":
file, err := c.FormFile("document")
// Save file to root directory:
return c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
})
```
## FormValue
Any form values can be retrieved by name, the **first** value from the given key is returned.
```go title="Signature"
func (c Ctx) FormValue(key string, defaultValue ...string) string
```
```go title="Example"
app.Post("/", func(c fiber.Ctx) error {
// Get first value from form field "name":
c.FormValue("name")
// => "john" or "" if not exist
// ..
})
```
:::info
Returned value is only valid within the handler. Do not store any references.
Make copies or use the [**`Immutable`**](./ctx.md) setting instead. [Read more...](../#zero-allocation)
:::
## Fresh
When the response is still **fresh** in the client's cache **true** is returned, otherwise **false** is returned to indicate that the client cache is now stale and the full response should be sent.
When a client sends the Cache-Control: no-cache request header to indicate an end-to-end reload request, `Fresh` will return false to make handling these requests transparent.
Read more on [https://expressjs.com/en/4x/api.html\#req.fresh](https://expressjs.com/en/4x/api.html#req.fresh)
```go title="Signature"
func (c Ctx) Fresh() bool
```
## Get
Returns the HTTP request header specified by the field.
:::tip
The match is **case-insensitive**.
:::
```go title="Signature"
func (c Ctx) Get(key string, defaultValue ...string) string
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
c.Get("Content-Type") // "text/plain"
c.Get("CoNtEnT-TypE") // "text/plain"
c.Get("something", "john") // "john"
// ..
})
```
:::info
Returned value is only valid within the handler. Do not store any references.
Make copies or use the [**`Immutable`**](./ctx.md) setting instead. [Read more...](../#zero-allocation)
:::
## GetReqHeaders
Returns the HTTP request headers as a map. Since a header can be set multiple times in a single request, the values of the map are slices of strings containing all the different values of the header.
```go title="Signature"
func (c Ctx) GetReqHeaders() map[string][]string
```
:::info
Returned value is only valid within the handler. Do not store any references.
Make copies or use the [**`Immutable`**](./ctx.md) setting instead. [Read more...](../#zero-allocation)
:::
## GetRespHeader
Returns the HTTP response header specified by the field.
:::tip
The match is **case-insensitive**.
:::
```go title="Signature"
func (c Ctx) GetRespHeader(key string, defaultValue ...string) string
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
c.GetRespHeader("X-Request-Id") // "8d7ad5e3-aaf3-450b-a241-2beb887efd54"
c.GetRespHeader("Content-Type") // "text/plain"
c.GetRespHeader("something", "john") // "john"
// ..
})
```
:::info
Returned value is only valid within the handler. Do not store any references.
Make copies or use the [**`Immutable`**](./ctx.md) setting instead. [Read more...](../#zero-allocation)
:::
## GetRespHeaders
Returns the HTTP response headers as a map. Since a header can be set multiple times in a single request, the values of the map are slices of strings containing all the different values of the header.
```go title="Signature"
func (c Ctx) GetRespHeaders() map[string][]string
```
:::info
Returned value is only valid within the handler. Do not store any references.
Make copies or use the [**`Immutable`**](./ctx.md) setting instead. [Read more...](../#zero-allocation)
:::
## GetRouteURL
Generates URLs to named routes, with parameters. URLs are relative, for example: "/user/1831"
```go title="Signature"
func (c Ctx) GetRouteURL(routeName string, params Map) (string, error)
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Home page")
}).Name("home")
app.Get("/user/:id", func(c fiber.Ctx) error {
return c.SendString(c.Params("id"))
}).Name("user.show")
app.Get("/test", func(c fiber.Ctx) error {
location, _ := c.GetRouteURL("user.show", fiber.Map{"id": 1})
return c.SendString(location)
})
// /test returns "/user/1"
```
## Host
Returns the host derived from the [Host](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Host) HTTP header.
In a network context, [`Host`](#host) refers to the combination of a hostname and potentially a port number used for connecting, while [`Hostname`](#hostname) refers specifically to the name assigned to a device on a network, excluding any port information.
```go title="Signature"
func (c Ctx) Host() string
```
```go title="Example"
// GET http://google.com:8080/search
app.Get("/", func(c fiber.Ctx) error {
c.Host() // "google.com:8080"
c.Hostname() // "google.com"
// ...
})
```
:::info
Returned value is only valid within the handler. Do not store any references.
Make copies or use the [**`Immutable`**](./ctx.md) setting instead. [Read more...](../#zero-allocation)
:::
## Hostname
Returns the hostname derived from the [Host](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Host) HTTP header.
```go title="Signature"
func (c Ctx) Hostname() string
```
```go title="Example"
// GET http://google.com/search
app.Get("/", func(c fiber.Ctx) error {
c.Hostname() // "google.com"
// ...
})
```
:::info
Returned value is only valid within the handler. Do not store any references.
Make copies or use the [**`Immutable`**](./ctx.md) setting instead. [Read more...](../#zero-allocation)
:::
## IP
Returns the remote IP address of the request.
```go title="Signature"
func (c Ctx) IP() string
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
c.IP() // "127.0.0.1"
// ...
})
```
When registering the proxy request header in the fiber app, the ip address of the header is returned [(Fiber configuration)](fiber.md#proxyheader)
```go
app := fiber.New(fiber.Config{
ProxyHeader: fiber.HeaderXForwardedFor,
})
```
## IPs
Returns an array of IP addresses specified in the [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For) request header.
```go title="Signature"
func (c Ctx) IPs() []string
```
```go title="Example"
// X-Forwarded-For: proxy1, 127.0.0.1, proxy3
app.Get("/", func(c fiber.Ctx) error {
c.IPs() // ["proxy1", "127.0.0.1", "proxy3"]
// ...
})
```
:::caution
Improper use of the X-Forwarded-For header can be a security risk. For details, see the [Security and privacy concerns](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For#security_and_privacy_concerns) section.
:::
## Is
Returns the matching **content type**, if the incoming request’s [Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) HTTP header field matches the [MIME type](https://developer.mozilla.org/ru/docs/Web/HTTP/Basics_of_HTTP/MIME_types) specified by the type parameter.
:::info
If the request has **no** body, it returns **false**.
:::
```go title="Signature"
func (c Ctx) Is(extension string) bool
```
```go title="Example"
// Content-Type: text/html; charset=utf-8
app.Get("/", func(c fiber.Ctx) error {
c.Is("html") // true
c.Is(".html") // true
c.Is("json") // false
// ...
})
```
## IsFromLocal
Returns true if request came from localhost
```go title="Signature"
func (c Ctx) IsFromLocal() bool {
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
// If request came from localhost, return true else return false
c.IsFromLocal()
// ...
})
```
## IsProxyTrusted
Checks trustworthiness of remote ip.
If [`EnableTrustedProxyCheck`](fiber.md#enabletrustedproxycheck) false, it returns true
IsProxyTrusted can check remote ip by proxy ranges and ip map.
```go title="Signature"
func (c Ctx) IsProxyTrusted() bool
```
```go title="Example"
app := fiber.New(fiber.Config{
// EnableTrustedProxyCheck enables the trusted proxy check
EnableTrustedProxyCheck: true,
// TrustedProxies is a list of trusted proxy IP addresses
TrustedProxies: []string{"0.8.0.0", "0.8.0.1"},
})
app.Get("/", func(c fiber.Ctx) error {
// If request came from trusted proxy, return true else return false
c.IsProxyTrusted()
// ...
})
```
## JSON
Converts any **interface** or **string** to JSON using the [encoding/json](https://pkg.go.dev/encoding/json) package.
:::info
JSON also sets the content header to the `ctype` parameter. If no `ctype` is passed in, the header is set to `application/json`.
:::
```go title="Signature"
func (c Ctx) JSON(data any, ctype ...string) error
```
```go title="Example"
type SomeStruct struct {
Name string
Age uint8
}
app.Get("/json", func(c fiber.Ctx) error {
// Create data struct:
data := SomeStruct{
Name: "Grame",
Age: 20,
}
return c.JSON(data)
// => Content-Type: application/json
// => "{"Name": "Grame", "Age": 20}"
return c.JSON(fiber.Map{
"name": "Grame",
"age": 20,
})
// => Content-Type: application/json
// => "{"name": "Grame", "age": 20}"
return c.JSON(fiber.Map{
"type": "https://example.com/probs/out-of-credit",
"title": "You do not have enough credit.",
"status": 403,
"detail": "Your current balance is 30, but that costs 50.",
"instance": "/account/12345/msgs/abc",
}, "application/problem+json")
// => Content-Type: application/problem+json
// => "{
// => "type": "https://example.com/probs/out-of-credit",
// => "title": "You do not have enough credit.",
// => "status": 403,
// => "detail": "Your current balance is 30, but that costs 50.",
// => "instance": "/account/12345/msgs/abc",
// => }"
})
```
## JSONP
Sends a JSON response with JSONP support. This method is identical to [JSON](ctx.md#json), except that it opts-in to JSONP callback support. By default, the callback name is simply callback.
Override this by passing a **named string** in the method.
```go title="Signature"
func (c Ctx) JSONP(data any, callback ...string) error
```
```go title="Example"
type SomeStruct struct {
name string
age uint8
}
app.Get("/", func(c fiber.Ctx) error {
// Create data struct:
data := SomeStruct{
name: "Grame",
age: 20,
}
return c.JSONP(data)
// => callback({"name": "Grame", "age": 20})
return c.JSONP(data, "customFunc")
// => customFunc({"name": "Grame", "age": 20})
})
```
## Links
Joins the links followed by the property to populate the response’s [Link](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link) HTTP header field.
```go title="Signature"
func (c Ctx) Links(link ...string)
```
```go title="Example"
app.Get("/", func(c fiber.Ctx) error {
c.Links(
"http://api.example.com/users?page=2", "next",
"http://api.example.com/users?page=5", "last",
)
// Link: <http://api.example.com/users?page=2>; rel="next",
// <http://api.example.com/users?page=5>; rel="last"
// ...
})
```
## Locals
A method that stores variables scoped to the request and, therefore, are available only to the routes that match the request. The stored variables are removed after the request is handled. If any of the stored data implements the `io.Closer` interface, its `Close` method will be called before it's removed.
:::tip
This is useful if you want to pass some **specific** data to the next middleware. Remember to perform type assertions when retrieving the data to ensure it is of the expected type. You can also use a non-exported type as a key to avoid collisions.
:::
```go title="Signature"
func (c Ctx) Locals(key any, value ...any) any
```
```go title="Example"
// keyType is an unexported type for keys defined in this package.
// This prevents collisions with keys defined in other packages.
type keyType int
// userKey is the key for user.User values in Contexts. It is
// unexported; clients use user.NewContext and user.FromContext
// instead of using this key directly.
var userKey keyType
app.Use(func(c fiber.Ctx) error {
c.Locals(userKey, "admin") // Stores the string "admin" under a non-exported type key
return c.Next()
})
app.Get("/admin", func(c fiber.Ctx) error {
user, ok := c.Locals(userKey).(string) // Retrieves the data stored under the key and performs a type assertion
if ok && user == "admin" {
return c.Status(fiber.StatusOK).SendString("Welcome, admin!")
}
return c.SendStatus(fiber.StatusForbidden)
})