github.com/gofiber/fiber/v2@v2.47.0/docs/api/ctx.md (about) 1 --- 2 id: ctx 3 title: đź§ Ctx 4 description: >- 5 The Ctx struct represents the Context which hold the HTTP request and 6 response. It has methods for the request query string, parameters, body, HTTP 7 headers, and so on. 8 sidebar_position: 3 9 --- 10 11 ## Accepts 12 13 Checks, if the specified **extensions** or **content** **types** are acceptable. 14 15 :::info 16 Based on the request’s [Accept](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept) HTTP header. 17 ::: 18 19 ```go title="Signature" 20 func (c *Ctx) Accepts(offers ...string) string 21 func (c *Ctx) AcceptsCharsets(offers ...string) string 22 func (c *Ctx) AcceptsEncodings(offers ...string) string 23 func (c *Ctx) AcceptsLanguages(offers ...string) string 24 ``` 25 26 ```go title="Example" 27 // Accept: text/html, application/json; q=0.8, text/plain; q=0.5; charset="utf-8" 28 29 app.Get("/", func(c *fiber.Ctx) error { 30 c.Accepts("html") // "html" 31 c.Accepts("text/html") // "text/html" 32 c.Accepts("json", "text") // "json" 33 c.Accepts("application/json") // "application/json" 34 c.Accepts("text/plain", "application/json") // "application/json", due to quality 35 c.Accepts("image/png") // "" 36 c.Accepts("png") // "" 37 // ... 38 }) 39 ``` 40 41 ```go title="Example 2" 42 // Accept: text/html, text/*, application/json, */*; q=0 43 44 app.Get("/", func(c *fiber.Ctx) error { 45 c.Accepts("text/plain", "application/json") // "application/json", due to specificity 46 c.Accepts("application/json", "text/html") // "text/html", due to first match 47 c.Accepts("image/png") // "", due to */* without q factor 0 is Not Acceptable 48 // ... 49 }) 50 ``` 51 52 Fiber provides similar functions for the other accept headers. 53 54 ```go 55 // Accept-Charset: utf-8, iso-8859-1;q=0.2 56 // Accept-Encoding: gzip, compress;q=0.2 57 // Accept-Language: en;q=0.8, nl, ru 58 59 app.Get("/", func(c *fiber.Ctx) error { 60 c.AcceptsCharsets("utf-16", "iso-8859-1") 61 // "iso-8859-1" 62 63 c.AcceptsEncodings("compress", "br") 64 // "compress" 65 66 c.AcceptsLanguages("pt", "nl", "ru") 67 // "nl" 68 // ... 69 }) 70 ``` 71 72 ## AllParams 73 74 Params is used to get all route parameters. 75 Using Params method to get params. 76 77 ```go title="Signature" 78 func (c *Ctx) AllParams() map[string]string 79 ``` 80 81 ```go title="Example" 82 // GET http://example.com/user/fenny 83 app.Get("/user/:name", func(c *fiber.Ctx) error { 84 c.AllParams() // "{"name": "fenny"}" 85 86 // ... 87 }) 88 89 // GET http://example.com/user/fenny/123 90 app.Get("/user/*", func(c *fiber.Ctx) error { 91 c.AllParams() // "{"*1": "fenny/123"}" 92 93 // ... 94 }) 95 ``` 96 97 ## App 98 99 Returns the [\*App](ctx.md) reference so you could easily access all application settings. 100 101 ```go title="Signature" 102 func (c *Ctx) App() *App 103 ``` 104 105 ```go title="Example" 106 app.Get("/stack", func(c *fiber.Ctx) error { 107 return c.JSON(c.App().Stack()) 108 }) 109 ``` 110 111 ## Append 112 113 Appends the specified **value** to the HTTP response header field. 114 115 :::caution 116 If the header is **not** already set, it creates the header with the specified value. 117 ::: 118 119 ```go title="Signature" 120 func (c *Ctx) Append(field string, values ...string) 121 ``` 122 123 ```go title="Example" 124 app.Get("/", func(c *fiber.Ctx) error { 125 c.Append("Link", "http://google.com", "http://localhost") 126 // => Link: http://localhost, http://google.com 127 128 c.Append("Link", "Test") 129 // => Link: http://localhost, http://google.com, Test 130 131 // ... 132 }) 133 ``` 134 135 ## Attachment 136 137 Sets the HTTP response [Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header field to `attachment`. 138 139 ```go title="Signature" 140 func (c *Ctx) Attachment(filename ...string) 141 ``` 142 143 ```go title="Example" 144 app.Get("/", func(c *fiber.Ctx) error { 145 c.Attachment() 146 // => Content-Disposition: attachment 147 148 c.Attachment("./upload/images/logo.png") 149 // => Content-Disposition: attachment; filename="logo.png" 150 // => Content-Type: image/png 151 152 // ... 153 }) 154 ``` 155 156 ## BaseURL 157 158 Returns the base URL \(**protocol** + **host**\) as a `string`. 159 160 ```go title="Signature" 161 func (c *Ctx) BaseURL() string 162 ``` 163 164 ```go title="Example" 165 // GET https://example.com/page#chapter-1 166 167 app.Get("/", func(c *fiber.Ctx) error { 168 c.BaseURL() // https://example.com 169 // ... 170 }) 171 ``` 172 173 ## Bind 174 Add vars to default view var map binding to template engine. 175 Variables are read by the Render method and may be overwritten. 176 177 ```go title="Signature" 178 func (c *Ctx) Bind(vars Map) error 179 ``` 180 181 ```go title="Example" 182 app.Use(func(c *fiber.Ctx) error { 183 c.Bind(fiber.Map{ 184 "Title": "Hello, World!", 185 }) 186 }) 187 188 app.Get("/", func(c *fiber.Ctx) error { 189 return c.Render("xxx.tmpl", fiber.Map{}) // Render will use Title variable 190 }) 191 ``` 192 193 ## Body 194 195 Returns the raw request **body**. 196 197 ```go title="Signature" 198 func (c *Ctx) Body() []byte 199 ``` 200 201 ```go title="Example" 202 // curl -X POST http://localhost:8080 -d user=john 203 204 app.Post("/", func(c *fiber.Ctx) error { 205 // Get raw body from POST request: 206 return c.Send(c.Body()) // []byte("user=john") 207 }) 208 ``` 209 210 > _Returned value is only valid within the handler. Do not store any references. 211 > Make copies or use the_ [_**`Immutable`**_](ctx.md) _setting instead._ [_Read more..._](../#zero-allocation) 212 213 ## BodyParser 214 215 Binds the request body to a struct. 216 217 It is important to specify the correct struct tag based on the content type to be parsed. For example, if you want to parse a JSON body with a field called Pass, you would use a struct field of `json:"pass"`. 218 219 | content-type | struct tag | 220 |---|---| 221 | `application/x-www-form-urlencoded` | form | 222 | `multipart/form-data` | form | 223 | `application/json` | json | 224 | `application/xml` | xml | 225 | `text/xml` | xml | 226 227 ```go title="Signature" 228 func (c *Ctx) BodyParser(out interface{}) error 229 ``` 230 231 ```go title="Example" 232 // Field names should start with an uppercase letter 233 type Person struct { 234 Name string `json:"name" xml:"name" form:"name"` 235 Pass string `json:"pass" xml:"pass" form:"pass"` 236 } 237 238 app.Post("/", func(c *fiber.Ctx) error { 239 p := new(Person) 240 241 if err := c.BodyParser(p); err != nil { 242 return err 243 } 244 245 log.Println(p.Name) // john 246 log.Println(p.Pass) // doe 247 248 // ... 249 }) 250 251 // Run tests with the following curl commands 252 253 // curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"pass\":\"doe\"}" localhost:3000 254 255 // curl -X POST -H "Content-Type: application/xml" --data "<login><name>john</name><pass>doe</pass></login>" localhost:3000 256 257 // curl -X POST -H "Content-Type: application/x-www-form-urlencoded" --data "name=john&pass=doe" localhost:3000 258 259 // curl -X POST -F name=john -F pass=doe http://localhost:3000 260 261 // curl -X POST "http://localhost:3000/?name=john&pass=doe" 262 ``` 263 264 > _Returned value is only valid within the handler. Do not store any references. 265 > Make copies or use the_ [_**`Immutable`**_](ctx.md) _setting instead._ [_Read more..._](../#zero-allocation) 266 267 ## ClearCookie 268 269 Expire a client cookie \(_or all cookies if left empty\)_ 270 271 ```go title="Signature" 272 func (c *Ctx) ClearCookie(key ...string) 273 ``` 274 275 ```go title="Example" 276 app.Get("/", func(c *fiber.Ctx) error { 277 // Clears all cookies: 278 c.ClearCookie() 279 280 // Expire specific cookie by name: 281 c.ClearCookie("user") 282 283 // Expire multiple cookies by names: 284 c.ClearCookie("token", "session", "track_id", "version") 285 // ... 286 }) 287 ``` 288 289 :::caution 290 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. 291 ::: 292 293 ```go title="Example" 294 app.Get("/set", func(c *fiber.Ctx) error { 295 c.Cookie(&fiber.Cookie{ 296 Name: "token", 297 Value: "randomvalue", 298 Expires: time.Now().Add(24 * time.Hour), 299 HTTPOnly: true, 300 SameSite: "lax", 301 }) 302 303 // ... 304 }) 305 306 app.Get("/delete", func(c *fiber.Ctx) error { 307 c.Cookie(&fiber.Cookie{ 308 Name: "token", 309 // Set expiry date to the past 310 Expires: time.Now().Add(-(time.Hour * 2)), 311 HTTPOnly: true, 312 SameSite: "lax", 313 }) 314 315 // ... 316 }) 317 ``` 318 319 ## ClientHelloInfo 320 321 ClientHelloInfo contains information from a ClientHello message in order to guide application logic in the GetCertificate and GetConfigForClient callbacks. 322 You can refer to the [ClientHelloInfo](https://golang.org/pkg/crypto/tls/#ClientHelloInfo) struct documentation for more information on the returned struct. 323 324 ```go title="Signature" 325 func (c *Ctx) ClientHelloInfo() *tls.ClientHelloInfo 326 ``` 327 328 ```go title="Example" 329 // GET http://example.com/hello 330 app.Get("/hello", func(c *fiber.Ctx) error { 331 chi := c.ClientHelloInfo() 332 // ... 333 }) 334 ``` 335 336 ## Context 337 338 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. 339 340 ```go title="Signature" 341 func (c *Ctx) Context() *fasthttp.RequestCtx 342 ``` 343 344 :::info 345 Please read the [Fasthttp Documentation](https://pkg.go.dev/github.com/valyala/fasthttp?tab=doc) for more information. 346 ::: 347 348 ## Cookie 349 350 Set cookie 351 352 ```go title="Signature" 353 func (c *Ctx) Cookie(cookie *Cookie) 354 ``` 355 356 ```go 357 type Cookie struct { 358 Name string `json:"name"` 359 Value string `json:"value"` 360 Path string `json:"path"` 361 Domain string `json:"domain"` 362 MaxAge int `json:"max_age"` 363 Expires time.Time `json:"expires"` 364 Secure bool `json:"secure"` 365 HTTPOnly bool `json:"http_only"` 366 SameSite string `json:"same_site"` 367 SessionOnly bool `json:"session_only"` 368 } 369 ``` 370 371 ```go title="Example" 372 app.Get("/", func(c *fiber.Ctx) error { 373 // Create cookie 374 cookie := new(fiber.Cookie) 375 cookie.Name = "john" 376 cookie.Value = "doe" 377 cookie.Expires = time.Now().Add(24 * time.Hour) 378 379 // Set cookie 380 c.Cookie(cookie) 381 // ... 382 }) 383 ``` 384 385 ## Cookies 386 387 Get cookie value by key, you could pass an optional default value that will be returned if the cookie key does not exist. 388 389 ```go title="Signature" 390 func (c *Ctx) Cookies(key string, defaultValue ...string) string 391 ``` 392 393 ```go title="Example" 394 app.Get("/", func(c *fiber.Ctx) error { 395 // Get cookie by key: 396 c.Cookies("name") // "john" 397 c.Cookies("empty", "doe") // "doe" 398 // ... 399 }) 400 ``` 401 402 > _Returned value is only valid within the handler. Do not store any references. 403 > Make copies or use the_ [_**`Immutable`**_](ctx.md) _setting instead._ [_Read more..._](../#zero-allocation) 404 405 ## Download 406 407 Transfers the file from path as an `attachment`. 408 409 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_\). 410 411 Override this default with the **filename** parameter. 412 413 ```go title="Signature" 414 func (c *Ctx) Download(file string, filename ...string) error 415 ``` 416 417 ```go title="Example" 418 app.Get("/", func(c *fiber.Ctx) error { 419 return c.Download("./files/report-12345.pdf"); 420 // => Download report-12345.pdf 421 422 return c.Download("./files/report-12345.pdf", "report.pdf"); 423 // => Download report.pdf 424 }) 425 ``` 426 427 ## Format 428 429 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. 430 431 :::info 432 If the header is **not** specified or there is **no** proper format, **text/plain** is used. 433 ::: 434 435 ```go title="Signature" 436 func (c *Ctx) Format(body interface{}) error 437 ``` 438 439 ```go title="Example" 440 app.Get("/", func(c *fiber.Ctx) error { 441 // Accept: text/plain 442 c.Format("Hello, World!") 443 // => Hello, World! 444 445 // Accept: text/html 446 c.Format("Hello, World!") 447 // => <p>Hello, World!</p> 448 449 // Accept: application/json 450 c.Format("Hello, World!") 451 // => "Hello, World!" 452 // .. 453 }) 454 ``` 455 456 ## FormFile 457 458 MultipartForm files can be retrieved by name, the **first** file from the given key is returned. 459 460 ```go title="Signature" 461 func (c *Ctx) FormFile(key string) (*multipart.FileHeader, error) 462 ``` 463 464 ```go title="Example" 465 app.Post("/", func(c *fiber.Ctx) error { 466 // Get first file from form field "document": 467 file, err := c.FormFile("document") 468 469 // Save file to root directory: 470 return c.SaveFile(file, fmt.Sprintf("./%s", file.Filename)) 471 }) 472 ``` 473 474 ## FormValue 475 476 Any form values can be retrieved by name, the **first** value from the given key is returned. 477 478 ```go title="Signature" 479 func (c *Ctx) FormValue(key string, defaultValue ...string) string 480 ``` 481 482 ```go title="Example" 483 app.Post("/", func(c *fiber.Ctx) error { 484 // Get first value from form field "name": 485 c.FormValue("name") 486 // => "john" or "" if not exist 487 488 // .. 489 }) 490 ``` 491 492 > _Returned value is only valid within the handler. Do not store any references. 493 > Make copies or use the_ [_**`Immutable`**_](ctx.md) _setting instead._ [_Read more..._](../#zero-allocation) 494 495 ## Fresh 496 497 [https://expressjs.com/en/4x/api.html\#req.fresh](https://expressjs.com/en/4x/api.html#req.fresh) 498 499 ```go title="Signature" 500 func (c *Ctx) Fresh() bool 501 ``` 502 503 ## Get 504 505 Returns the HTTP request header specified by the field. 506 507 :::tip 508 The match is **case-insensitive**. 509 ::: 510 511 ```go title="Signature" 512 func (c *Ctx) Get(key string, defaultValue ...string) string 513 ``` 514 515 ```go title="Example" 516 app.Get("/", func(c *fiber.Ctx) error { 517 c.Get("Content-Type") // "text/plain" 518 c.Get("CoNtEnT-TypE") // "text/plain" 519 c.Get("something", "john") // "john" 520 // .. 521 }) 522 ``` 523 524 > _Returned value is only valid within the handler. Do not store any references. 525 > Make copies or use the_ [_**`Immutable`**_](ctx.md) _setting instead._ [_Read more..._](../#zero-allocation) 526 527 ## GetReqHeaders 528 529 Returns the HTTP request headers. 530 531 ```go title="Signature" 532 func (c *Ctx) GetReqHeaders() map[string]string 533 ``` 534 535 ## GetRespHeader 536 537 Returns the HTTP response header specified by the field. 538 539 :::tip 540 The match is **case-insensitive**. 541 ::: 542 543 ```go title="Signature" 544 func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string 545 ``` 546 547 ```go title="Example" 548 app.Get("/", func(c *fiber.Ctx) error { 549 c.GetRespHeader("X-Request-Id") // "8d7ad5e3-aaf3-450b-a241-2beb887efd54" 550 c.GetRespHeader("Content-Type") // "text/plain" 551 c.GetRespHeader("something", "john") // "john" 552 // .. 553 }) 554 ``` 555 556 > _Returned value is only valid within the handler. Do not store any references. 557 > Make copies or use the_ [_**`Immutable`**_](ctx.md) _setting instead._ [_Read more..._](../#zero-allocation) 558 559 ## GetRespHeaders 560 561 Returns the HTTP response headers. 562 563 ```go title="Signature" 564 func (c *Ctx) GetRespHeaders() map[string]string 565 ``` 566 567 ## GetRouteURL 568 569 Generates URLs to named routes, with parameters. URLs are relative, for example: "/user/1831" 570 571 ```go title="Signature" 572 func (c *Ctx) GetRouteURL(routeName string, params Map) (string, error) 573 ``` 574 575 ```go title="Example" 576 app.Get("/", func(c *fiber.Ctx) error { 577 return c.SendString("Home page") 578 }).Name("home") 579 580 app.Get("/user/:id", func(c *fiber.Ctx) error { 581 return c.SendString(c.Params("id")) 582 }).Name("user.show") 583 584 app.Get("/test", func(c *fiber.Ctx) error { 585 location, _ := c.GetRouteURL("user.show", fiber.Map{"id": 1}) 586 return c.SendString(location) 587 }) 588 589 // /test returns "/user/1" 590 ``` 591 592 ## Hostname 593 594 Returns the hostname derived from the [Host](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Host) HTTP header. 595 596 ```go title="Signature" 597 func (c *Ctx) Hostname() string 598 ``` 599 600 ```go title="Example" 601 // GET http://google.com/search 602 603 app.Get("/", func(c *fiber.Ctx) error { 604 c.Hostname() // "google.com" 605 606 // ... 607 }) 608 ``` 609 610 > _Returned value is only valid within the handler. Do not store any references. 611 > Make copies or use the_ [_**`Immutable`**_](ctx.md) _setting instead._ [_Read more..._](../#zero-allocation) 612 613 ## IP 614 615 Returns the remote IP address of the request. 616 617 ```go title="Signature" 618 func (c *Ctx) IP() string 619 ``` 620 621 ```go title="Example" 622 app.Get("/", func(c *fiber.Ctx) error { 623 c.IP() // "127.0.0.1" 624 625 // ... 626 }) 627 ``` 628 629 When registering the proxy request header in the fiber app, the ip address of the header is returned [(Fiber configuration)](fiber.md#config) 630 631 ```go 632 app := fiber.New(fiber.Config{ 633 ProxyHeader: fiber.HeaderXForwardedFor, 634 }) 635 ``` 636 637 ## IPs 638 639 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. 640 641 ```go title="Signature" 642 func (c *Ctx) IPs() []string 643 ``` 644 645 ```go title="Example" 646 // X-Forwarded-For: proxy1, 127.0.0.1, proxy3 647 648 app.Get("/", func(c *fiber.Ctx) error { 649 c.IPs() // ["proxy1", "127.0.0.1", "proxy3"] 650 651 // ... 652 }) 653 ``` 654 655 ## Is 656 657 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. 658 659 :::info 660 If the request has **no** body, it returns **false**. 661 ::: 662 663 ```go title="Signature" 664 func (c *Ctx) Is(extension string) bool 665 ``` 666 667 ```go title="Example" 668 // Content-Type: text/html; charset=utf-8 669 670 app.Get("/", func(c *fiber.Ctx) error { 671 c.Is("html") // true 672 c.Is(".html") // true 673 c.Is("json") // false 674 675 // ... 676 }) 677 ``` 678 679 ## IsFromLocal 680 681 Returns true if request came from localhost 682 ```go title="Signature" 683 func (c *Ctx) IsFromLocal() bool { 684 ``` 685 686 ```go title="Example" 687 688 app.Get("/", func(c *fiber.Ctx) error { 689 // If request came from localhost, return true else return false 690 c.IsFromLocal() 691 692 // ... 693 }) 694 ``` 695 696 ## JSON 697 698 Converts any **interface** or **string** to JSON using the [goccy/go-json](https://github.com/goccy/go-json) package. 699 700 :::info 701 JSON also sets the content header to **application/json**. 702 ::: 703 704 ```go title="Signature" 705 func (c *Ctx) JSON(data interface{}) error 706 ``` 707 708 ```go title="Example" 709 type SomeStruct struct { 710 Name string 711 Age uint8 712 } 713 714 app.Get("/json", func(c *fiber.Ctx) error { 715 // Create data struct: 716 data := SomeStruct{ 717 Name: "Grame", 718 Age: 20, 719 } 720 721 return c.JSON(data) 722 // => Content-Type: application/json 723 // => "{"Name": "Grame", "Age": 20}" 724 725 return c.JSON(fiber.Map{ 726 "name": "Grame", 727 "age": 20, 728 }) 729 // => Content-Type: application/json 730 // => "{"name": "Grame", "age": 20}" 731 }) 732 ``` 733 734 ## JSONP 735 736 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. 737 738 Override this by passing a **named string** in the method. 739 740 ```go title="Signature" 741 func (c *Ctx) JSONP(data interface{}, callback ...string) error 742 ``` 743 744 ```go title="Example" 745 type SomeStruct struct { 746 name string 747 age uint8 748 } 749 750 app.Get("/", func(c *fiber.Ctx) error { 751 // Create data struct: 752 data := SomeStruct{ 753 name: "Grame", 754 age: 20, 755 } 756 757 return c.JSONP(data) 758 // => callback({"name": "Grame", "age": 20}) 759 760 return c.JSONP(data, "customFunc") 761 // => customFunc({"name": "Grame", "age": 20}) 762 }) 763 ``` 764 765 ## Links 766 767 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. 768 769 ```go title="Signature" 770 func (c *Ctx) Links(link ...string) 771 ``` 772 773 ```go title="Example" 774 app.Get("/", func(c *fiber.Ctx) error { 775 c.Links( 776 "http://api.example.com/users?page=2", "next", 777 "http://api.example.com/users?page=5", "last", 778 ) 779 // Link: <http://api.example.com/users?page=2>; rel="next", 780 // <http://api.example.com/users?page=5>; rel="last" 781 782 // ... 783 }) 784 ``` 785 786 ## Locals 787 788 A method that stores variables scoped to the request and, therefore, are available only to the routes that match the request. 789 790 :::tip 791 This is useful if you want to pass some **specific** data to the next middleware. 792 ::: 793 794 ```go title="Signature" 795 func (c *Ctx) Locals(key interface{}, value ...interface{}) interface{} 796 ``` 797 798 ```go title="Example" 799 app.Use(func(c *fiber.Ctx) error { 800 c.Locals("user", "admin") 801 return c.Next() 802 }) 803 804 app.Get("/admin", func(c *fiber.Ctx) error { 805 if c.Locals("user") == "admin" { 806 return c.Status(fiber.StatusOK).SendString("Welcome, admin!") 807 } 808 return c.SendStatus(fiber.StatusForbidden) 809 810 }) 811 ``` 812 813 ## Location 814 815 Sets the response [Location](https://developer.mozilla.org/ru/docs/Web/HTTP/Headers/Location) HTTP header to the specified path parameter. 816 817 ```go title="Signature" 818 func (c *Ctx) Location(path string) 819 ``` 820 821 ```go title="Example" 822 app.Post("/", func(c *fiber.Ctx) error { 823 c.Location("http://example.com") 824 825 c.Location("/foo/bar") 826 827 return nil 828 }) 829 ``` 830 831 ## Method 832 833 Returns a string corresponding to the HTTP method of the request: `GET`, `POST`, `PUT`, and so on. 834 Optionally, you could override the method by passing a string. 835 836 ```go title="Signature" 837 func (c *Ctx) Method(override ...string) string 838 ``` 839 840 ```go title="Example" 841 app.Post("/", func(c *fiber.Ctx) error { 842 c.Method() // "POST" 843 844 c.Method("GET") 845 c.Method() // GET 846 847 // ... 848 }) 849 ``` 850 851 ## MultipartForm 852 853 To access multipart form entries, you can parse the binary with `MultipartForm()`. This returns a `map[string][]string`, so given a key, the value will be a string slice. 854 855 ```go title="Signature" 856 func (c *Ctx) MultipartForm() (*multipart.Form, error) 857 ``` 858 859 ```go title="Example" 860 app.Post("/", func(c *fiber.Ctx) error { 861 // Parse the multipart form: 862 if form, err := c.MultipartForm(); err == nil { 863 // => *multipart.Form 864 865 if token := form.Value["token"]; len(token) > 0 { 866 // Get key value: 867 fmt.Println(token[0]) 868 } 869 870 // Get all files from "documents" key: 871 files := form.File["documents"] 872 // => []*multipart.FileHeader 873 874 // Loop through files: 875 for _, file := range files { 876 fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0]) 877 // => "tutorial.pdf" 360641 "application/pdf" 878 879 // Save the files to disk: 880 if err := c.SaveFile(file, fmt.Sprintf("./%s", file.Filename)); err != nil { 881 return err 882 } 883 } 884 } 885 886 return err 887 }) 888 ``` 889 890 ## Next 891 892 When **Next** is called, it executes the next method in the stack that matches the current route. You can pass an error struct within the method that will end the chaining and call the [error handler](https://docs.gofiber.io/guide/error-handling). 893 894 ```go title="Signature" 895 func (c *Ctx) Next() error 896 ``` 897 898 ```go title="Example" 899 app.Get("/", func(c *fiber.Ctx) error { 900 fmt.Println("1st route!") 901 return c.Next() 902 }) 903 904 app.Get("*", func(c *fiber.Ctx) error { 905 fmt.Println("2nd route!") 906 return c.Next() 907 }) 908 909 app.Get("/", func(c *fiber.Ctx) error { 910 fmt.Println("3rd route!") 911 return c.SendString("Hello, World!") 912 }) 913 ``` 914 915 ## OriginalURL 916 917 Returns the original request URL. 918 919 ```go title="Signature" 920 func (c *Ctx) OriginalURL() string 921 ``` 922 923 ```go title="Example" 924 // GET http://example.com/search?q=something 925 926 app.Get("/", func(c *fiber.Ctx) error { 927 c.OriginalURL() // "/search?q=something" 928 929 // ... 930 }) 931 ``` 932 933 > _Returned value is only valid within the handler. Do not store any references. 934 > Make copies or use the_ [_**`Immutable`**_](ctx.md) _setting instead._ [_Read more..._](../#zero-allocation) 935 936 ## Params 937 938 Method can be used to get the route parameters, you could pass an optional default value that will be returned if the param key does not exist. 939 940 :::info 941 Defaults to empty string \(`""`\), if the param **doesn't** exist. 942 ::: 943 944 ```go title="Signature" 945 func (c *Ctx) Params(key string, defaultValue ...string) string 946 ``` 947 948 ```go title="Example" 949 // GET http://example.com/user/fenny 950 app.Get("/user/:name", func(c *fiber.Ctx) error { 951 c.Params("name") // "fenny" 952 953 // ... 954 }) 955 956 // GET http://example.com/user/fenny/123 957 app.Get("/user/*", func(c *fiber.Ctx) error { 958 c.Params("*") // "fenny/123" 959 c.Params("*1") // "fenny/123" 960 961 // ... 962 }) 963 ``` 964 965 Unnamed route parameters\(\*, +\) can be fetched by the **character** and the **counter** in the route. 966 967 ```go title="Example" 968 // ROUTE: /v1/*/shop/* 969 // GET: /v1/brand/4/shop/blue/xs 970 c.Params("*1") // "brand/4" 971 c.Params("*2") // "blue/xs" 972 ``` 973 974 For reasons of **downward compatibility**, the first parameter segment for the parameter character can also be accessed without the counter. 975 976 ```go title="Example" 977 app.Get("/v1/*/shop/*", func(c *fiber.Ctx) error { 978 c.Params("*") // outputs the values of the first wildcard segment 979 }) 980 ``` 981 982 > _Returned value is only valid within the handler. Do not store any references. 983 > Make copies or use the_ [_**`Immutable`**_](ctx.md) _setting instead._ [_Read more..._](../#zero-allocation) 984 985 ## ParamsInt 986 987 Method can be used to get an integer from the route parameters. 988 Please note if that parameter is not in the request, zero 989 will be returned. If the parameter is NOT a number, zero and an error 990 will be returned 991 992 :::info 993 Defaults to the integer zero \(`0`\), if the param **doesn't** exist. 994 ::: 995 996 ```go title="Signature" 997 func (c *Ctx) ParamsInt(key string) (int, error) 998 ``` 999 1000 ```go title="Example" 1001 // GET http://example.com/user/123 1002 app.Get("/user/:id", func(c *fiber.Ctx) error { 1003 id, err := c.ParamsInt("id") // int 123 and no error 1004 1005 // ... 1006 }) 1007 1008 ``` 1009 1010 This method is equivalent of using `atoi` with ctx.Params 1011 1012 ## ParamsParser 1013 This method is similar to BodyParser, but for path parameters. It is important to use the struct tag "params". For example, if you want to parse a path parameter with a field called Pass, you would use a struct field of params:"pass" 1014 1015 ```go title="Signature" 1016 func (c *Ctx) ParamsParser(out interface{}) error 1017 ``` 1018 1019 ```go title="Example" 1020 // GET http://example.com/user/111 1021 app.Get("/user/:id", func(c *fiber.Ctx) error { 1022 param := struct {ID uint `params:"id"`}{} 1023 1024 c.ParamsParser(¶m) // "{"id": 111}" 1025 1026 // ... 1027 }) 1028 1029 ``` 1030 1031 ## Path 1032 1033 Contains the path part of the request URL. Optionally, you could override the path by passing a string. For internal redirects, you might want to call [RestartRouting](ctx.md#restartrouting) instead of [Next](ctx.md#next). 1034 1035 ```go title="Signature" 1036 func (c *Ctx) Path(override ...string) string 1037 ``` 1038 1039 ```go title="Example" 1040 // GET http://example.com/users?sort=desc 1041 1042 app.Get("/users", func(c *fiber.Ctx) error { 1043 c.Path() // "/users" 1044 1045 c.Path("/john") 1046 c.Path() // "/john" 1047 1048 // ... 1049 }) 1050 ``` 1051 1052 ## Protocol 1053 1054 Contains the request protocol string: `http` or `https` for **TLS** requests. 1055 1056 ```go title="Signature" 1057 func (c *Ctx) Protocol() string 1058 ``` 1059 1060 ```go title="Example" 1061 // GET http://example.com 1062 1063 app.Get("/", func(c *fiber.Ctx) error { 1064 c.Protocol() // "http" 1065 1066 // ... 1067 }) 1068 ``` 1069 1070 ## Queries 1071 1072 Queries is a function that returns an object containing a property for each query string parameter in the route. 1073 1074 ```go title="Signature" 1075 func (c *Ctx) Queries() (map[string]string, error) 1076 ``` 1077 1078 ```go title="Example" 1079 // GET http://example.com/?name=alex&want_pizza=false&id= 1080 1081 app.Get("/", func(c *fiber.Ctx) error { 1082 m := c.Queries() 1083 m["name"] // "alex" 1084 m["want_pizza"] // "false" 1085 m["id"] // "" 1086 // ... 1087 }) 1088 ``` 1089 1090 ```go title="Example" 1091 // GET http://example.com/?field1=value1&field1=value2&field2=value3 1092 1093 app.Get("/", func (c *fiber.Ctx) error { 1094 m := c.Queries() 1095 m["field1"] // "value2" 1096 m["field2"] // value3 1097 }) 1098 ``` 1099 1100 ```go title="Example" 1101 // GET http://example.com/?list_a=1&list_a=2&list_a=3&list_b[]=1&list_b[]=2&list_b[]=3&list_c=1,2,3 1102 1103 app.Get("/", func(c *fiber.Ctx) error { 1104 m := c.Queries() 1105 m["list_a"] // "3" 1106 m["list_b[]"] // "3" 1107 m["list_c"] // "1,2,3" 1108 }) 1109 ``` 1110 1111 ```go title="Example" 1112 // GET /api/posts?filters.author.name=John&filters.category.name=Technology 1113 1114 app.Get("/", func(c *fiber.Ctx) error { 1115 m := c.Queries() 1116 m["filters.author.name"] // John 1117 m["filters.category.name"] // Technology 1118 }) 1119 ``` 1120 1121 ```go title="Example" 1122 // GET /api/posts?tags=apple,orange,banana&filters[tags]=apple,orange,banana&filters[category][name]=fruits&filters.tags=apple,orange,banana&filters.category.name=fruits 1123 1124 app.Get("/", func(c *fiber.Ctx) error { 1125 m := c.Queries() 1126 m["tags"] // apple,orange,banana 1127 m["filters[tags]"] // apple,orange,banana 1128 m["filters[category][name]"] // fruits 1129 m["filters.tags"] // apple,orange,banana 1130 m["filters.category.name"] // fruits 1131 }) 1132 ``` 1133 1134 ## Query 1135 1136 This property is an object containing a property for each query string parameter in the route, you could pass an optional default value that will be returned if the query key does not exist. 1137 1138 :::info 1139 If there is **no** query string, it returns an **empty string**. 1140 ::: 1141 1142 ```go title="Signature" 1143 func (c *Ctx) Query(key string, defaultValue ...string) string 1144 ``` 1145 1146 ```go title="Example" 1147 // GET http://example.com/?order=desc&brand=nike 1148 1149 app.Get("/", func(c *fiber.Ctx) error { 1150 c.Query("order") // "desc" 1151 c.Query("brand") // "nike" 1152 c.Query("empty", "nike") // "nike" 1153 1154 // ... 1155 }) 1156 ``` 1157 1158 > _Returned value is only valid within the handler. Do not store any references. 1159 > Make copies or use the_ [_**`Immutable`**_](ctx.md) _setting instead._ [_Read more..._](../#zero-allocation) 1160 1161 ## QueryBool 1162 1163 This property is an object containing a property for each query boolean parameter in the route, you could pass an optional default value that will be returned if the query key does not exist. 1164 1165 1166 :::caution 1167 Please note if that parameter is not in the request, false will be returned. 1168 If the parameter is not a boolean, it is still tried to be converted and usually returned as false. 1169 ::: 1170 1171 ```go title="Signature" 1172 func (c *Ctx) QueryBool(key string, defaultValue ...bool) bool 1173 ``` 1174 1175 ```go title="Example" 1176 // GET http://example.com/?name=alex&want_pizza=false&id= 1177 1178 app.Get("/", func(c *fiber.Ctx) error { 1179 c.QueryBool("want_pizza") // false 1180 c.QueryBool("want_pizza", true) // false 1181 c.QueryBool("name") // false 1182 c.QueryBool("name", true) // true 1183 c.QueryBool("id") // false 1184 c.QueryBool("id", true) // true 1185 1186 // ... 1187 }) 1188 ``` 1189 1190 ## QueryFloat 1191 1192 This property is an object containing a property for each query float64 parameter in the route, you could pass an optional default value that will be returned if the query key does not exist. 1193 1194 :::caution 1195 Please note if that parameter is not in the request, zero will be returned. 1196 If the parameter is not a number, it is still tried to be converted and usually returned as 1. 1197 ::: 1198 1199 :::info 1200 Defaults to the float64 zero \(`0`\), if the param **doesn't** exist. 1201 ::: 1202 1203 ```go title="Signature" 1204 func (c *Ctx) QueryFloat(key string, defaultValue ...float64) float64 1205 ``` 1206 1207 ```go title="Example" 1208 // GET http://example.com/?name=alex&amount=32.23&id= 1209 1210 app.Get("/", func(c *fiber.Ctx) error { 1211 c.QueryFloat("amount") // 32.23 1212 c.QueryFloat("amount", 3) // 32.23 1213 c.QueryFloat("name", 1) // 1 1214 c.QueryFloat("name") // 0 1215 c.QueryFloat("id", 3) // 3 1216 1217 // ... 1218 }) 1219 ``` 1220 1221 1222 ## QueryInt 1223 1224 This property is an object containing a property for each query integer parameter in the route, you could pass an optional default value that will be returned if the query key does not exist. 1225 1226 1227 :::caution 1228 Please note if that parameter is not in the request, zero will be returned. 1229 If the parameter is not a number, it is still tried to be converted and usually returned as 1. 1230 ::: 1231 1232 :::info 1233 Defaults to the integer zero \(`0`\), if the param **doesn't** exist. 1234 ::: 1235 1236 ```go title="Signature" 1237 func (c *Ctx) QueryInt(key string, defaultValue ...int) int 1238 ``` 1239 1240 ```go title="Example" 1241 // GET http://example.com/?name=alex&wanna_cake=2&id= 1242 1243 app.Get("/", func(c *fiber.Ctx) error { 1244 c.QueryInt("wanna_cake", 1) // 2 1245 c.QueryInt("name", 1) // 1 1246 c.QueryInt("id", 1) // 1 1247 c.QueryInt("id") // 0 1248 1249 // ... 1250 }) 1251 ``` 1252 1253 ## QueryParser 1254 1255 This method is similar to [BodyParser](ctx.md#bodyparser), but for query parameters. 1256 It is important to use the struct tag "query". For example, if you want to parse a query parameter with a field called Pass, you would use a struct field of `query:"pass"`. 1257 1258 ```go title="Signature" 1259 func (c *Ctx) QueryParser(out interface{}) error 1260 ``` 1261 1262 ```go title="Example" 1263 // Field names should start with an uppercase letter 1264 type Person struct { 1265 Name string `query:"name"` 1266 Pass string `query:"pass"` 1267 Products []string `query:"products"` 1268 } 1269 1270 app.Get("/", func(c *fiber.Ctx) error { 1271 p := new(Person) 1272 1273 if err := c.QueryParser(p); err != nil { 1274 return err 1275 } 1276 1277 log.Println(p.Name) // john 1278 log.Println(p.Pass) // doe 1279 log.Println(p.Products) // [shoe, hat] 1280 1281 // ... 1282 }) 1283 // Run tests with the following curl command 1284 1285 // curl "http://localhost:3000/?name=john&pass=doe&products=shoe,hat" 1286 ``` 1287 1288 ## Range 1289 1290 A struct containing the type and a slice of ranges will be returned. 1291 1292 ```go title="Signature" 1293 func (c *Ctx) Range(size int) (Range, error) 1294 ``` 1295 1296 ```go title="Example" 1297 // Range: bytes=500-700, 700-900 1298 app.Get("/", func(c *fiber.Ctx) error { 1299 b := c.Range(1000) 1300 if b.Type == "bytes" { 1301 for r := range r.Ranges { 1302 fmt.Println(r) 1303 // [500, 700] 1304 } 1305 } 1306 }) 1307 ``` 1308 1309 ## Redirect 1310 1311 Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code. 1312 1313 :::info 1314 If **not** specified, status defaults to **302 Found**. 1315 ::: 1316 1317 ```go title="Signature" 1318 func (c *Ctx) Redirect(location string, status ...int) error 1319 ``` 1320 1321 ```go title="Example" 1322 app.Get("/coffee", func(c *fiber.Ctx) error { 1323 return c.Redirect("/teapot") 1324 }) 1325 1326 app.Get("/teapot", func(c *fiber.Ctx) error { 1327 return c.Status(fiber.StatusTeapot).Send("🍵 short and stout 🍵") 1328 }) 1329 ``` 1330 1331 ```go title="More examples" 1332 app.Get("/", func(c *fiber.Ctx) error { 1333 return c.Redirect("/foo/bar") 1334 return c.Redirect("../login") 1335 return c.Redirect("http://example.com") 1336 return c.Redirect("http://example.com", 301) 1337 }) 1338 ``` 1339 1340 ## RedirectToRoute 1341 1342 Redirects to the specific route along with the parameters and with specified status, a positive integer that corresponds to an HTTP status code. 1343 1344 :::info 1345 If **not** specified, status defaults to **302 Found**. 1346 ::: 1347 1348 :::info 1349 If you want to send queries to route, you must add **"queries"** key typed as **map[string]string** to params. 1350 ::: 1351 1352 ```go title="Signature" 1353 func (c *Ctx) RedirectToRoute(routeName string, params fiber.Map, status ...int) error 1354 ``` 1355 1356 ```go title="Example" 1357 app.Get("/", func(c *fiber.Ctx) error { 1358 // /user/fiber 1359 return c.RedirectToRoute("user", fiber.Map{ 1360 "name": "fiber" 1361 }) 1362 }) 1363 1364 app.Get("/with-queries", func(c *fiber.Ctx) error { 1365 // /user/fiber?data[0][name]=john&data[0][age]=10&test=doe 1366 return c.RedirectToRoute("user", fiber.Map{ 1367 "name": "fiber", 1368 "queries": map[string]string{"data[0][name]": "john", "data[0][age]": "10", "test": "doe"}, 1369 }) 1370 }) 1371 1372 app.Get("/user/:name", func(c *fiber.Ctx) error { 1373 return c.SendString(c.Params("name")) 1374 }).Name("user") 1375 ``` 1376 1377 ## RedirectBack 1378 1379 Redirects back to refer URL. It redirects to fallback URL if refer header doesn't exists, with specified status, a positive integer that corresponds to an HTTP status code. 1380 1381 :::info 1382 If **not** specified, status defaults to **302 Found**. 1383 ::: 1384 1385 ```go title="Signature" 1386 func (c *Ctx) RedirectBack(fallback string, status ...int) error 1387 ``` 1388 1389 ```go title="Example" 1390 app.Get("/", func(c *fiber.Ctx) error { 1391 return c.SendString("Home page") 1392 }) 1393 app.Get("/test", func(c *fiber.Ctx) error { 1394 c.Set("Content-Type", "text/html") 1395 return c.SendString(`<a href="/back">Back</a>`) 1396 }) 1397 1398 app.Get("/back", func(c *fiber.Ctx) error { 1399 return c.RedirectBack("/") 1400 }) 1401 ``` 1402 1403 ## Render 1404 1405 Renders a view with data and sends a `text/html` response. By default `Render` uses the default [**Go Template engine**](https://pkg.go.dev/html/template/). If you want to use another View engine, please take a look at our [**Template middleware**](https://github.com/gofiber/template). 1406 1407 ```go title="Signature" 1408 func (c *Ctx) Render(name string, bind interface{}, layouts ...string) error 1409 ``` 1410 1411 ## Request 1412 1413 Request return the [\*fasthttp.Request](https://godoc.org/github.com/valyala/fasthttp#Request) pointer 1414 1415 ```go title="Signature" 1416 func (c *Ctx) Request() *fasthttp.Request 1417 ``` 1418 1419 ```go title="Example" 1420 app.Get("/", func(c *fiber.Ctx) error { 1421 c.Request().Header.Method() 1422 // => []byte("GET") 1423 }) 1424 ``` 1425 1426 ## ReqHeaderParser 1427 1428 This method is similar to [BodyParser](ctx.md#bodyparser), but for request headers. 1429 It is important to use the struct tag "reqHeader". For example, if you want to parse a request header with a field called Pass, you would use a struct field of `reqHeader:"pass"`. 1430 1431 ```go title="Signature" 1432 func (c *Ctx) ReqHeaderParser(out interface{}) error 1433 ``` 1434 1435 ```go title="Example" 1436 // Field names should start with an uppercase letter 1437 type Person struct { 1438 Name string `reqHeader:"name"` 1439 Pass string `reqHeader:"pass"` 1440 Products []string `reqHeader:"products"` 1441 } 1442 1443 app.Get("/", func(c *fiber.Ctx) error { 1444 p := new(Person) 1445 1446 if err := c.ReqHeaderParser(p); err != nil { 1447 return err 1448 } 1449 1450 log.Println(p.Name) // john 1451 log.Println(p.Pass) // doe 1452 log.Println(p.Products) // [shoe, hat] 1453 1454 // ... 1455 }) 1456 // Run tests with the following curl command 1457 1458 // curl "http://localhost:3000/" -H "name: john" -H "pass: doe" -H "products: shoe,hat" 1459 ``` 1460 1461 ## Response 1462 1463 Response return the [\*fasthttp.Response](https://godoc.org/github.com/valyala/fasthttp#Response) pointer 1464 1465 ```go title="Signature" 1466 func (c *Ctx) Response() *fasthttp.Response 1467 ``` 1468 1469 ```go title="Example" 1470 app.Get("/", func(c *fiber.Ctx) error { 1471 c.Response().BodyWriter().Write([]byte("Hello, World!")) 1472 // => "Hello, World!" 1473 return nil 1474 }) 1475 ``` 1476 1477 ## RestartRouting 1478 1479 Instead of executing the next method when calling [Next](ctx.md#next), **RestartRouting** restarts execution from the first method that matches the current route. This may be helpful after overriding the path, i. e. an internal redirect. Note that handlers might be executed again which could result in an infinite loop. 1480 1481 ```go title="Signature" 1482 func (c *Ctx) RestartRouting() error 1483 ``` 1484 1485 ```go title="Example" 1486 app.Get("/new", func(c *fiber.Ctx) error { 1487 return c.SendString("From /new") 1488 }) 1489 1490 app.Get("/old", func(c *fiber.Ctx) error { 1491 c.Path("/new") 1492 return c.RestartRouting() 1493 }) 1494 ``` 1495 1496 ## Route 1497 1498 Returns the matched [Route](https://pkg.go.dev/github.com/gofiber/fiber?tab=doc#Route) struct. 1499 1500 ```go title="Signature" 1501 func (c *Ctx) Route() *Route 1502 ``` 1503 1504 ```go title="Example" 1505 // http://localhost:8080/hello 1506 1507 1508 app.Get("/hello/:name", func(c *fiber.Ctx) error { 1509 r := c.Route() 1510 fmt.Println(r.Method, r.Path, r.Params, r.Handlers) 1511 // GET /hello/:name handler [name] 1512 1513 // ... 1514 }) 1515 ``` 1516 1517 :::caution 1518 Do not rely on `c.Route()` in middlewares **before** calling `c.Next()` - `c.Route()` returns the **last executed route**. 1519 ::: 1520 1521 ```go title="Example" 1522 func MyMiddleware() fiber.Handler { 1523 return func(c *fiber.Ctx) error { 1524 beforeNext := c.Route().Path // Will be '/' 1525 err := c.Next() 1526 afterNext := c.Route().Path // Will be '/hello/:name' 1527 return err 1528 } 1529 } 1530 ``` 1531 1532 ## SaveFile 1533 1534 Method is used to save **any** multipart file to disk. 1535 1536 ```go title="Signature" 1537 func (c *Ctx) SaveFile(fh *multipart.FileHeader, path string) error 1538 ``` 1539 1540 ```go title="Example" 1541 app.Post("/", func(c *fiber.Ctx) error { 1542 // Parse the multipart form: 1543 if form, err := c.MultipartForm(); err == nil { 1544 // => *multipart.Form 1545 1546 // Get all files from "documents" key: 1547 files := form.File["documents"] 1548 // => []*multipart.FileHeader 1549 1550 // Loop through files: 1551 for _, file := range files { 1552 fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0]) 1553 // => "tutorial.pdf" 360641 "application/pdf" 1554 1555 // Save the files to disk: 1556 if err := c.SaveFile(file, fmt.Sprintf("./%s", file.Filename)); err != nil { 1557 return err 1558 } 1559 } 1560 return err 1561 } 1562 }) 1563 ``` 1564 1565 ## SaveFileToStorage 1566 1567 Method is used to save **any** multipart file to an external storage system. 1568 1569 ```go title="Signature" 1570 func (c *Ctx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error 1571 ``` 1572 1573 ```go title="Example" 1574 storage := memory.New() 1575 1576 app.Post("/", func(c *fiber.Ctx) error { 1577 // Parse the multipart form: 1578 if form, err := c.MultipartForm(); err == nil { 1579 // => *multipart.Form 1580 1581 // Get all files from "documents" key: 1582 files := form.File["documents"] 1583 // => []*multipart.FileHeader 1584 1585 // Loop through files: 1586 for _, file := range files { 1587 fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0]) 1588 // => "tutorial.pdf" 360641 "application/pdf" 1589 1590 // Save the files to storage: 1591 if err := c.SaveFileToStorage(file, fmt.Sprintf("./%s", file.Filename), storage); err != nil { 1592 return err 1593 } 1594 } 1595 return err 1596 } 1597 }) 1598 ``` 1599 1600 ## Secure 1601 1602 A boolean property that is `true` , if a **TLS** connection is established. 1603 1604 ```go title="Signature" 1605 func (c *Ctx) Secure() bool 1606 ``` 1607 1608 ```go title="Example" 1609 // Secure() method is equivalent to: 1610 c.Protocol() == "https" 1611 ``` 1612 1613 ## Send 1614 1615 Sets the HTTP response body. 1616 1617 ```go title="Signature" 1618 func (c *Ctx) Send(body []byte) error 1619 ``` 1620 1621 ```go title="Example" 1622 app.Get("/", func(c *fiber.Ctx) error { 1623 return c.Send([]byte("Hello, World!")) // => "Hello, World!" 1624 }) 1625 ``` 1626 1627 Fiber also provides `SendString` and `SendStream` methods for raw inputs. 1628 1629 :::tip 1630 Use this if you **don't need** type assertion, recommended for **faster** performance. 1631 ::: 1632 1633 ```go title="Signature" 1634 func (c *Ctx) SendString(body string) error 1635 func (c *Ctx) SendStream(stream io.Reader, size ...int) error 1636 ``` 1637 1638 ```go title="Example" 1639 app.Get("/", func(c *fiber.Ctx) error { 1640 return c.SendString("Hello, World!") 1641 // => "Hello, World!" 1642 1643 return c.SendStream(bytes.NewReader([]byte("Hello, World!"))) 1644 // => "Hello, World!" 1645 }) 1646 ``` 1647 1648 ## SendFile 1649 1650 Transfers the file from the given path. Sets the [Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) response HTTP header field based on the **filenames** extension. 1651 1652 :::caution 1653 Method doesn´t use **gzipping** by default, set it to **true** to enable. 1654 ::: 1655 1656 ```go title="Signature" title="Signature" 1657 func (c *Ctx) SendFile(file string, compress ...bool) error 1658 ``` 1659 1660 ```go title="Example" 1661 app.Get("/not-found", func(c *fiber.Ctx) error { 1662 return c.SendFile("./public/404.html"); 1663 1664 // Disable compression 1665 return c.SendFile("./static/index.html", false); 1666 }) 1667 ``` 1668 1669 :::info 1670 If the file contains an url specific character you have to escape it before passing the file path into the `sendFile` function. 1671 ::: 1672 1673 ```go title="Example" 1674 app.Get("/file-with-url-chars", func(c *fiber.Ctx) error { 1675 return c.SendFile(url.PathEscape("hash_sign_#.txt")) 1676 }) 1677 ``` 1678 1679 ## SendStatus 1680 1681 Sets the status code and the correct status message in the body, if the response body is **empty**. 1682 1683 :::tip 1684 You can find all used status codes and messages [here](https://github.com/gofiber/fiber/blob/dffab20bcdf4f3597d2c74633a7705a517d2c8c2/utils.go#L183-L244). 1685 ::: 1686 1687 ```go title="Signature" 1688 func (c *Ctx) SendStatus(status int) error 1689 ``` 1690 1691 ```go title="Example" 1692 app.Get("/not-found", func(c *fiber.Ctx) error { 1693 return c.SendStatus(415) 1694 // => 415 "Unsupported Media Type" 1695 1696 c.SendString("Hello, World!") 1697 return c.SendStatus(415) 1698 // => 415 "Hello, World!" 1699 }) 1700 ``` 1701 1702 ## Set 1703 1704 Sets the response’s HTTP header field to the specified `key`, `value`. 1705 1706 ```go title="Signature" 1707 func (c *Ctx) Set(key string, val string) 1708 ``` 1709 1710 ```go title="Example" 1711 app.Get("/", func(c *fiber.Ctx) error { 1712 c.Set("Content-Type", "text/plain") 1713 // => "Content-type: text/plain" 1714 1715 // ... 1716 }) 1717 ``` 1718 1719 ## SetParserDecoder 1720 1721 Allow you to config BodyParser/QueryParser decoder, base on schema's options, providing possibility to add custom type for pausing. 1722 1723 ```go title="Signature" 1724 func SetParserDecoder(parserConfig fiber.ParserConfig{ 1725 IgnoreUnknownKeys bool, 1726 ParserType []fiber.ParserType{ 1727 Customtype interface{}, 1728 Converter func(string) reflect.Value, 1729 }, 1730 ZeroEmpty bool, 1731 SetAliasTag string, 1732 }) 1733 ``` 1734 1735 ```go title="Example" 1736 1737 type CustomTime time.Time 1738 1739 // String() returns the time in string 1740 func (ct *CustomTime) String() string { 1741 t := time.Time(*ct).String() 1742 return t 1743 } 1744 1745 // Register the converter for CustomTime type format as 2006-01-02 1746 var timeConverter = func(value string) reflect.Value { 1747 fmt.Println("timeConverter", value) 1748 if v, err := time.Parse("2006-01-02", value); err == nil { 1749 return reflect.ValueOf(v) 1750 } 1751 return reflect.Value{} 1752 } 1753 1754 customTime := fiber.ParserType{ 1755 Customtype: CustomTime{}, 1756 Converter: timeConverter, 1757 } 1758 1759 // Add setting to the Decoder 1760 fiber.SetParserDecoder(fiber.ParserConfig{ 1761 IgnoreUnknownKeys: true, 1762 ParserType: []fiber.ParserType{customTime}, 1763 ZeroEmpty: true, 1764 }) 1765 1766 // Example to use CustomType, you pause custom time format not in RFC3339 1767 type Demo struct { 1768 Date CustomTime `form:"date" query:"date"` 1769 Title string `form:"title" query:"title"` 1770 Body string `form:"body" query:"body"` 1771 } 1772 1773 app.Post("/body", func(c *fiber.Ctx) error { 1774 var d Demo 1775 c.BodyParser(&d) 1776 fmt.Println("d.Date", d.Date.String()) 1777 return c.JSON(d) 1778 }) 1779 1780 app.Get("/query", func(c *fiber.Ctx) error { 1781 var d Demo 1782 c.QueryParser(&d) 1783 fmt.Println("d.Date", d.Date.String()) 1784 return c.JSON(d) 1785 }) 1786 1787 // curl -X POST -F title=title -F body=body -F date=2021-10-20 http://localhost:3000/body 1788 1789 // curl -X GET "http://localhost:3000/query?title=title&body=body&date=2021-10-20" 1790 1791 ``` 1792 1793 1794 ## SetUserContext 1795 1796 Sets the user specified implementation for context interface. 1797 1798 ```go title="Signature" 1799 func (c *Ctx) SetUserContext(ctx context.Context) 1800 ``` 1801 1802 ```go title="Example" 1803 app.Get("/", func(c *fiber.Ctx) error { 1804 ctx := context.Background() 1805 c.SetUserContext(ctx) 1806 // Here ctx could be any context implementation 1807 1808 // ... 1809 }) 1810 ``` 1811 1812 ## Stale 1813 1814 [https://expressjs.com/en/4x/api.html\#req.stale](https://expressjs.com/en/4x/api.html#req.stale) 1815 1816 ```go title="Signature" 1817 func (c *Ctx) Stale() bool 1818 ``` 1819 1820 ## Status 1821 1822 Sets the HTTP status for the response. 1823 1824 :::info 1825 Method is a **chainable**. 1826 ::: 1827 1828 ```go title="Signature" 1829 func (c *Ctx) Status(status int) *Ctx 1830 ``` 1831 1832 ```go title="Example" 1833 app.Get("/fiber", func(c *fiber.Ctx) error { 1834 c.Status(fiber.StatusOK) 1835 return nil 1836 } 1837 1838 app.Get("/hello", func(c *fiber.Ctx) error { 1839 return c.Status(fiber.StatusBadRequest).SendString("Bad Request") 1840 } 1841 1842 app.Get("/world", func(c *fiber.Ctx) error { 1843 return c.Status(fiber.StatusNotFound).SendFile("./public/gopher.png") 1844 }) 1845 ``` 1846 1847 ## Subdomains 1848 1849 Returns a string slice of subdomains in the domain name of the request. 1850 1851 The application property subdomain offset, which defaults to `2`, is used for determining the beginning of the subdomain segments. 1852 1853 ```go title="Signature" 1854 func (c *Ctx) Subdomains(offset ...int) []string 1855 ``` 1856 1857 ```go title="Example" 1858 // Host: "tobi.ferrets.example.com" 1859 1860 app.Get("/", func(c *fiber.Ctx) error { 1861 c.Subdomains() // ["ferrets", "tobi"] 1862 c.Subdomains(1) // ["tobi"] 1863 1864 // ... 1865 }) 1866 ``` 1867 1868 ## Type 1869 1870 Sets the [Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) HTTP header to the MIME type listed [here](https://github.com/nginx/nginx/blob/master/conf/mime.types) specified by the file **extension**. 1871 1872 ```go title="Signature" 1873 func (c *Ctx) Type(ext string, charset ...string) *Ctx 1874 ``` 1875 1876 ```go title="Example" 1877 app.Get("/", func(c *fiber.Ctx) error { 1878 c.Type(".html") // => "text/html" 1879 c.Type("html") // => "text/html" 1880 c.Type("png") // => "image/png" 1881 1882 c.Type("json", "utf-8") // => "application/json; charset=utf-8" 1883 1884 // ... 1885 }) 1886 ``` 1887 1888 ## UserContext 1889 1890 UserContext returns a context implementation that was set by user earlier 1891 or returns a non-nil, empty context, if it was not set earlier. 1892 1893 ```go title="Signature" 1894 func (c *Ctx) UserContext() context.Context 1895 ``` 1896 1897 ```go title="Example" 1898 app.Get("/", func(c *fiber.Ctx) error { 1899 ctx := c.UserContext() 1900 // ctx is context implementation set by user 1901 1902 // ... 1903 }) 1904 ``` 1905 1906 ## Vary 1907 1908 Adds the given header field to the [Vary](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary) response header. This will append the header, if not already listed, otherwise leaves it listed in the current location. 1909 1910 :::info 1911 Multiple fields are **allowed**. 1912 ::: 1913 1914 ```go title="Signature" 1915 func (c *Ctx) Vary(fields ...string) 1916 ``` 1917 1918 ```go title="Example" 1919 app.Get("/", func(c *fiber.Ctx) error { 1920 c.Vary("Origin") // => Vary: Origin 1921 c.Vary("User-Agent") // => Vary: Origin, User-Agent 1922 1923 // No duplicates 1924 c.Vary("Origin") // => Vary: Origin, User-Agent 1925 1926 c.Vary("Accept-Encoding", "Accept") 1927 // => Vary: Origin, User-Agent, Accept-Encoding, Accept 1928 1929 // ... 1930 }) 1931 ``` 1932 1933 ## Write 1934 1935 Write adopts the Writer interface 1936 1937 ```go title="Signature" 1938 func (c *Ctx) Write(p []byte) (n int, err error) 1939 ``` 1940 1941 ```go title="Example" 1942 app.Get("/", func(c *fiber.Ctx) error { 1943 c.Write([]byte("Hello, World!")) // => "Hello, World!" 1944 1945 fmt.Fprintf(c, "%s\n", "Hello, World!") // "Hello, World!Hello, World!" 1946 }) 1947 ``` 1948 1949 ## Writef 1950 1951 Writef adopts the string with variables 1952 1953 ```go title="Signature" 1954 func (c *Ctx) Writef(f string, a ...interface{}) (n int, err error) 1955 ``` 1956 1957 ```go title="Example" 1958 app.Get("/", func(c *fiber.Ctx) error { 1959 world := "World!" 1960 c.Writef("Hello, %s", world) // => "Hello, World!" 1961 1962 fmt.Fprintf(c, "%s\n", "Hello, World!") // "Hello, World!Hello, World!" 1963 }) 1964 ``` 1965 1966 ## WriteString 1967 1968 WriteString adopts the string 1969 1970 ```go title="Signature" 1971 func (c *Ctx) WriteString(s string) (n int, err error) 1972 ``` 1973 1974 ```go title="Example" 1975 app.Get("/", func(c *fiber.Ctx) error { 1976 c.WriteString("Hello, World!") // => "Hello, World!" 1977 1978 fmt.Fprintf(c, "%s\n", "Hello, World!") // "Hello, World!Hello, World!" 1979 }) 1980 ``` 1981 1982 ## XHR 1983 1984 A Boolean property, that is `true`, if the request’s [X-Requested-With](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) header field is [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), indicating that the request was issued by a client library \(such as [jQuery](https://api.jquery.com/jQuery.ajax/)\). 1985 1986 ```go title="Signature" 1987 func (c *Ctx) XHR() bool 1988 ``` 1989 1990 ```go title="Example" 1991 // X-Requested-With: XMLHttpRequest 1992 1993 app.Get("/", func(c *fiber.Ctx) error { 1994 c.XHR() // true 1995 1996 // ... 1997 }) 1998 ``` 1999 2000 ## XML 2001 2002 Converts any **interface** or **string** to XML using the standard `encoding/xml` package. 2003 2004 :::info 2005 XML also sets the content header to **application/xml**. 2006 ::: 2007 2008 ```go title="Signature" 2009 func (c *Ctx) XML(data interface{}) error 2010 ``` 2011 2012 ```go title="Example" 2013 type SomeStruct struct { 2014 XMLName xml.Name `xml:"Fiber"` 2015 Name string `xml:"Name"` 2016 Age uint8 `xml:"Age"` 2017 } 2018 2019 app.Get("/", func(c *fiber.Ctx) error { 2020 // Create data struct: 2021 data := SomeStruct{ 2022 Name: "Grame", 2023 Age: 20, 2024 } 2025 2026 return c.XML(data) 2027 // <Fiber> 2028 // <Name>Grame</Name> 2029 // <Age>20</Age> 2030 // </Fiber> 2031 }) 2032 ```