description: >- The Ctx struct 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.

🧠 Context

Accepts

Checks, if the specified extensions or content types are acceptable.

Based on the request’s Accept HTTP header.

  1. c.Accepts(types ...string) string
  2. c.AcceptsCharsets(charsets ...string) string
  3. c.AcceptsEncodings(encodings ...string) string
  4. c.AcceptsLanguages(langs ...string) string
  1. // Accept: text/*, application/json
  2. app.Get("/", func(c *fiber.Ctx) {
  3. c.Accepts("html") // "html"
  4. c.Accepts("text/html") // "text/html"
  5. c.Accepts("json", "text") // "json"
  6. c.Accepts("application/json") // "application/json"
  7. c.Accepts("image/png") // ""
  8. c.Accepts("png") // ""
  9. })

Fiber provides similar functions for the other accept headers.

  1. // Accept-Charset: utf-8, iso-8859-1;q=0.2
  2. // Accept-Encoding: gzip, compress;q=0.2
  3. // Accept-Language: en;q=0.8, nl, ru
  4. app.Get("/", func(c *fiber.Ctx) {
  5. c.AcceptsCharsets("utf-16", "iso-8859-1")
  6. // "iso-8859-1"
  7. c.AcceptsEncodings("compress", "br")
  8. // "compress"
  9. c.AcceptsLanguages("pt", "nl", "ru")
  10. // "nl"
  11. })

Append

Appends the specified value to the HTTP response header field.

If the header is not already set, it creates the header with the specified value.

  1. c.Append(field, values ...string)
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Append("Link", "http://google.com", "http://localhost")
  3. // => Link: http://localhost, http://google.com
  4. c.Append("Link", "Test")
  5. // => Link: http://localhost, http://google.com, Test
  6. })

Attachment

Sets the HTTP response Content-Disposition header field to attachment.

  1. c.Attachment(file ...string)
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Attachment()
  3. // => Content-Disposition: attachment
  4. c.Attachment("./upload/images/logo.png")
  5. // => Content-Disposition: attachment; filename="logo.png"
  6. // => Content-Type: image/png
  7. })

BaseURL

Returns base URL (protocol + host) as a string.

  1. c.BaseURL() string
  1. // GET https://example.com/page#chapter-1
  2. app.Get("/", func(c *fiber.Ctx) {
  3. c.BaseURL() // https://example.com
  4. })

Body

Contains the raw body submitted in a POST request.

  1. c.Body() string
  1. // curl -X POST http://localhost:8080 -d user=john
  2. app.Post("/", func(c *fiber.Ctx) {
  3. // Get raw body from POST request:
  4. c.Body() // user=john
  5. })

BodyParser

Binds the request body to a struct. BodyParser supports decoding query parameters and the following content types based on the Content-Type header:

  • application/json
  • application/xml
  • application/x-www-form-urlencoded
  • multipart/form-data
  1. c.BodyParser(out interface{}) error
  1. // Field names should start with an uppercase letter
  2. type Person struct {
  3. Name string `json:"name" xml:"name" form:"name" query:"name"`
  4. Pass string `json:"pass" xml:"pass" form:"pass" query:"pass"`
  5. }
  6. app.Post("/", func(c *fiber.Ctx) {
  7. p := new(Person)
  8. if err := c.BodyParser(p); err != nil {
  9. log.Fatal(err)
  10. }
  11. log.Println(p.Name) // john
  12. log.Println(p.Pass) // doe
  13. })
  14. // Run tests with the following curl commands
  15. // curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"pass\":\"doe\"}" localhost:3000
  16. // curl -X POST -H "Content-Type: application/xml" --data "<login><name>john</name><pass>doe</pass></login>" localhost:3000
  17. // curl -X POST -H "Content-Type: application/x-www-form-urlencoded" --data "name=john&pass=doe" localhost:3000
  18. // curl -X POST -F name=john -F pass=doe http://localhost:3000
  19. // curl -X POST "http://localhost:3000/?name=john&pass=doe"

ClearCookie

Expire a client cookie (or all cookies if left empty)

  1. c.ClearCookie(key ...string)
  1. app.Get("/", func(c *fiber.Ctx) {
  2. // Clears all cookies:
  3. c.ClearCookie()
  4. // Expire specific cookie by name:
  5. c.ClearCookie("user")
  6. // Expire multiple cookies by names:
  7. c.ClearCookie("token", "session", "track_id", "version")
  8. })

Cookie

Set cookie

Signature

  1. c.Cookie(*Cookie)
  1. type Cookie struct {
  2. Name string
  3. Value string
  4. Path string
  5. Domain string
  6. Expires time.Time
  7. Secure bool
  8. HTTPOnly bool
  9. SameSite string // lax, strict, none
  10. }
  1. app.Get("/", func(c *fiber.Ctx) {
  2. // Create cookie
  3. cookie := new(fiber.Cookie)
  4. cookie.Name = "john"
  5. cookie.Value = "doe"
  6. cookie.Expires = time.Now().Add(24 * time.Hour)
  7. // Set cookie
  8. c.Cookie(cookie)
  9. })

Cookies

Get cookie value by key.

Signatures

  1. c.Cookies(key string) string
  1. app.Get("/", func(c *fiber.Ctx) {
  2. // Get cookie by key:
  3. c.Cookies("name") // "john"
  4. })

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.

  1. c.Download(path, filename ...string)
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Download("./files/report-12345.pdf")
  3. // => Download report-12345.pdf
  4. c.Download("./files/report-12345.pdf", "report.pdf")
  5. // => Download report.pdf
  6. })

Fasthttp

You can still access and use all Fasthttp methods and properties.

Signature

Please read the Fasthttp Documentation for more information.

Example

  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Fasthttp.Request.Header.Method()
  3. // => []byte("GET")
  4. c.Fasthttp.Response.Write([]byte("Hello, World!"))
  5. // => "Hello, World!"
  6. })

Error

This contains the error information that thrown by a panic or passed via the Next(err) method.

  1. c.Error() error
  1. func main() {
  2. app := fiber.New()
  3. app.Post("/api/register", func (c *fiber.Ctx) {
  4. if err := c.JSON(&User); err != nil {
  5. c.Next(err)
  6. }
  7. })
  8. app.Get("/api/user", func (c *fiber.Ctx) {
  9. if err := c.JSON(&User); err != nil {
  10. c.Next(err)
  11. }
  12. })
  13. app.Put("/api/update", func (c *fiber.Ctx) {
  14. if err := c.JSON(&User); err != nil {
  15. c.Next(err)
  16. }
  17. })
  18. app.Use("/api", func(c *fiber.Ctx) {
  19. c.Set("Content-Type", "application/json")
  20. c.Status(500).Send(c.Error())
  21. })
  22. app.Listen(":1337")
  23. }

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.

  1. c.Format(body interface{})
  1. app.Get("/", func(c *fiber.Ctx) {
  2. // Accept: text/plain
  3. c.Format("Hello, World!")
  4. // => Hello, World!
  5. // Accept: text/html
  6. c.Format("Hello, World!")
  7. // => <p>Hello, World!</p>
  8. // Accept: application/json
  9. c.Format("Hello, World!")
  10. // => "Hello, World!"
  11. })

FormFile

MultipartForm files can be retrieved by name, the first file from the given key is returned.

  1. c.FormFile(name string) (*multipart.FileHeader, error)
  1. app.Post("/", func(c *fiber.Ctx) {
  2. // Get first file from form field "document":
  3. file, err := c.FormFile("document")
  4. // Check for errors:
  5. if err == nil {
  6. // Save file to root directory:
  7. c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
  8. }
  9. })

FormValue

Any form values can be retrieved by name, the first value from the given key is returned.

  1. c.FormValue(name string) string
  1. app.Post("/", func(c *fiber.Ctx) {
  2. // Get first value from form field "name":
  3. c.FormValue("name")
  4. // => "john" or "" if not exist
  5. })

Fresh

https://expressjs.com/en/4x/api.html#req.fresh

Not implemented yet, pull requests are welcome!

Get

Returns the HTTP request header specified by field.

The match is case-insensitive.

  1. c.Get(field string) string
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Get("Content-Type") // "text/plain"
  3. c.Get("CoNtEnT-TypE") // "text/plain"
  4. c.Get("something") // ""
  5. })

Hostname

Contains the hostname derived from the Host HTTP header.

  1. c.Hostname() string
  1. // GET http://google.com/search
  2. app.Get("/", func(c *fiber.Ctx) {
  3. c.Hostname() // "google.com"
  4. })

IP

Returns the remote IP address of the request.

  1. c.IP() string
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.IP() // "127.0.0.1"
  3. })

IPs

Returns an array of IP addresses specified in the X-Forwarded-For request header.

  1. c.IPs() []string
  1. // X-Forwarded-For: proxy1, 127.0.0.1, proxy3
  2. app.Get("/", func(c *fiber.Ctx) {
  3. c.IPs() // ["proxy1", "127.0.0.1", "proxy3"]
  4. })

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.

If the request has no body, it returns false.

  1. c.Is(t string) bool
  1. // Content-Type: text/html; charset=utf-8
  2. app.Get("/", func(c *fiber.Ctx) {
  3. c.Is("html") // true
  4. c.Is(".html") // true
  5. c.Is("json") // false
  6. })

JSON

Converts any interface or string to JSON using Jsoniter.

JSON also sets the content header to application/json.

  1. c.JSON(v interface{}) error
  1. type SomeStruct struct {
  2. Name string
  3. Age uint8
  4. }
  5. app.Get("/json", func(c *fiber.Ctx) {
  6. // Create data struct:
  7. data := SomeStruct{
  8. Name: "Grame",
  9. Age: 20,
  10. }
  11. c.JSON(data)
  12. // => Content-Type: application/json
  13. // => "{"Name": "Grame", "Age": 20}"
  14. c.JSON(fiber.Map{
  15. "name": "Grame",
  16. "age": 20,
  17. })
  18. // => Content-Type: application/json
  19. // => "{"name": "Grame", "age": 20}"
  20. })

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.

Override this by passing a named string in the method.

  1. c.JSONP(v interface{}, callback ...string) error
  1. type SomeStruct struct {
  2. name string
  3. age uint8
  4. }
  5. app.Get("/", func(c *fiber.Ctx) {
  6. // Create data struct:
  7. data := SomeStruct{
  8. name: "Grame",
  9. age: 20,
  10. }
  11. c.JSONP(data)
  12. // => callback({"name": "Grame", "age": 20})
  13. c.JSONP(data, "customFunc")
  14. // => customFunc({"name": "Grame", "age": 20})
  15. })

Links

Joins the links followed by the property to populate the response’s Link HTTP header field.

  1. c.Links(link ...string)
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Link(
  3. "http://api.example.com/users?page=2", "next",
  4. "http://api.example.com/users?page=5", "last",
  5. )
  6. // Link: <http://api.example.com/users?page=2>; rel="next",
  7. // <http://api.example.com/users?page=5>; rel="last"
  8. })

Locals

Method that stores string variables scoped to the request and therefore available only to the routes that match the request.

This is useful, if you want to pass some specific data to the next middleware.

  1. c.Locals(key string, value ...interface{}) interface{}
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Locals("user", "admin")
  3. c.Next()
  4. })
  5. app.Get("/admin", func(c *fiber.Ctx) {
  6. if c.Locals("user") == "admin" {
  7. c.Status(200).Send("Welcome, admin!")
  8. } else {
  9. c.SendStatus(403)
  10. // => 403 Forbidden
  11. }
  12. })

Location

Sets the response Location HTTP header to the specified path parameter.

  1. c.Location(path string)
  1. app.Post("/", func(c *fiber.Ctx) {
  2. c.Location("http://example.com")
  3. c.Location("/foo/bar")
  4. })

Method

Contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.

  1. c.Method() string
  1. app.Post("/", func(c *fiber.Ctx) {
  2. c.Method() // "POST"
  3. })

MultipartForm

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.

  1. c.MultipartForm() (*multipart.Form, error)
  1. app.Post("/", func(c *fiber.Ctx) {
  2. // Parse the multipart form:
  3. if form, err := c.MultipartForm(); err == nil {
  4. // => *multipart.Form
  5. if token := form.Value["token"]; len(token) > 0 {
  6. // Get key value:
  7. fmt.Println(token[0])
  8. }
  9. // Get all files from "documents" key:
  10. files := form.File["documents"]
  11. // => []*multipart.FileHeader
  12. // Loop through files:
  13. for _, file := range files {
  14. fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0])
  15. // => "tutorial.pdf" 360641 "application/pdf"
  16. // Save the files to disk:
  17. c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
  18. }
  19. }
  20. })

Next

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 for custom error handling.

  1. c.Next(err ...error)
  1. app.Get("/", func(c *fiber.Ctx) {
  2. fmt.Println("1st route!")
  3. c.Next()
  4. })
  5. app.Get("*", func(c *fiber.Ctx) {
  6. fmt.Println("2nd route!")
  7. c.Next(fmt.Errorf("Some error"))
  8. })
  9. app.Get("/", func(c *fiber.Ctx) {
  10. fmt.Println(c.Error()) // => "Some error"
  11. fmt.Println("3rd route!")
  12. c.Send("Hello, World!")
  13. })

OriginalURL

Contains the original request URL.

  1. c.OriginalURL() string
  1. // GET http://example.com/search?q=something
  2. app.Get("/", func(c *fiber.Ctx) {
  3. c.OriginalURL() // "/search?q=something"
  4. })

Params

Method can be used to get the route parameters.

Defaults to empty string (""), if the param doesn’t exist.

  1. c.Params(param string) string
  1. // GET http://example.com/user/fenny
  2. app.Get("/user/:name", func(c *fiber.Ctx) {
  3. c.Params("name") // "fenny"
  4. })

Path

Contains the path part of the request URL.

  1. c.Path() string
  1. // GET http://example.com/users?sort=desc
  2. app.Get("/users", func(c *fiber.Ctx) {
  3. c.Path() // "/users"
  4. })

Protocol

Contains the request protocol string: http or https for TLS requests.

  1. c.Protocol() string
  1. // GET http://example.com
  2. app.Get("/", func(c *fiber.Ctx) {
  3. c.Protocol() // "http"
  4. })

Query

This property is an object containing a property for each query string parameter in the route.

If there is no query string, it returns an empty string.

  1. c.Query(parameter string) string
  1. // GET http://example.com/shoes?order=desc&brand=nike
  2. app.Get("/", func(c *fiber.Ctx) {
  3. c.Query("order") // "desc"
  4. c.Query("brand") // "nike"
  5. })

Range

An struct containg the type and a slice of ranges will be returned.

  1. c.Range(int size)
  1. // Range: bytes=500-700, 700-900
  2. app.Get("/", func(c *fiber.Ctx) {
  3. b := c.Range(1000)
  4. if b.Type == "bytes" {
  5. for r := range r.Ranges {
  6. fmt.Println(r)
  7. // [500, 700]
  8. }
  9. }
  10. })

Redirect

Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code.

If not specified, status defaults to 302 Found.

  1. c.Redirect(path string, status ...int)
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Redirect("/foo/bar")
  3. c.Redirect("../login")
  4. c.Redirect("http://example.com")
  5. c.Redirect("http://example.com", 301)
  6. })

Render

Renders a template with data and sends a text/html response. By default Render uses the default Go Template engine. If you want to use another engine, please take a look at our Template middleware.

  1. c.Render(file string, data interface{}) error

Route

Contains the matched Route struct.

  1. c.Route() *Route
  1. // http://localhost:8080/hello
  2. app.Get("/hello", func(c *fiber.Ctx) {
  3. r := c.Route()
  4. fmt.Println(r.Method, r.Path, r.Params, r.Regexp, r.Handler)
  5. })
  6. app.Post("/:api?", func(c *fiber.Ctx) {
  7. c.Route()
  8. // => {GET /hello [] nil 0x7b49e0}
  9. })

SaveFile

Method is used to save any multipart file to disk.

  1. c.SaveFile(fh *multipart.FileHeader, path string)
  1. app.Post("/", func(c *fiber.Ctx) {
  2. // Parse the multipart form:
  3. if form, err := c.MultipartForm(); err == nil {
  4. // => *multipart.Form
  5. // Get all files from "documents" key:
  6. files := form.File["documents"]
  7. // => []*multipart.FileHeader
  8. // Loop through files:
  9. for _, file := range files {
  10. fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0])
  11. // => "tutorial.pdf" 360641 "application/pdf"
  12. // Save the files to disk:
  13. c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
  14. }
  15. }
  16. })

Secure

A boolean property, that is true , if a TLS connection is established.

  1. c.Secure() bool
  1. // Secure() method is equivalent to:
  2. c.Protocol() == "https"

Send

Sets the HTTP response body. The Send body can be of any type.

Send doesn’t append like the Write method.

  1. c.Send(body ...interface{})
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Send("Hello, World!") // => "Hello, World!"
  3. c.Send([]byte("Hello, World!")) // => "Hello, World!"
  4. c.Send(123) // => 123
  5. })

Fiber also provides SendBytes & SendString methods for raw inputs.

Use this, if you don’t need type assertion, recommended for faster performance.

  1. c.SendBytes(b []byte)
  2. c.SendString(s string)
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.SendByte([]byte("Hello, World!"))
  3. // => "Hello, World!"
  4. c.SendString("Hello, World!")
  5. // => "Hello, World!"
  6. })

SendFile

Transfers the file from the given path. Sets the Content-Type response HTTP header field based on the filenames extension.

Method use gzipping by default, set it to true to disable.

  1. c.SendFile(path string, gzip ...bool)
  1. app.Get("/not-found", func(c *fiber.Ctx) {
  2. c.SendFile("./public/404.html")
  3. // Disable gzipping:
  4. c.SendFile("./static/index.html", true)
  5. })

SendStatus

Sets the status code and the correct status message in the body, if the response body is empty.

You can find all used status codes and messages here.

  1. c.SendStatus(status int)
  1. app.Get("/not-found", func(c *fiber.Ctx) {
  2. c.SendStatus(415)
  3. // => 415 "Unsupported Media Type"
  4. c.Send("Hello, World!")
  5. c.SendStatus(415)
  6. // => 415 "Hello, World!"
  7. })

Set

Sets the response’s HTTP header field to the specified key, value.

  1. c.Set(field, value string)
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Set("Content-Type", "text/plain")
  3. // => "Content-type: text/plain"
  4. })

Stale

https://expressjs.com/en/4x/api.html#req.fresh

Not implemented yet, pull requests are welcome!

Status

Sets the HTTP status for the response.

Method is a chainable.

  1. c.Status(status int)
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Status(200)
  3. c.Status(400).Send("Bad Request")
  4. c.Status(404).SendFile("./public/gopher.png")
  5. })

Subdomains

An array of subdomains in the domain name of the request.

The application property subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.

  1. c.Subdomains(offset ...int) []string
  1. // Host: "tobi.ferrets.example.com"
  2. app.Get("/", func(c *fiber.Ctx) {
  3. c.Subdomains() // ["ferrets", "tobi"]
  4. c.Subdomains(1) // ["tobi"]
  5. })

Type

Sets the Content-Type HTTP header to the MIME type listed here specified by the file extension.

  1. c.Type(t string) string
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Type(".html") // => "text/html"
  3. c.Type("html") // => "text/html"
  4. c.Type("json") // => "application/json"
  5. c.Type("png") // => "image/png"
  6. })

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.

Multiple fields are allowed.

  1. c.Vary(field ...string)
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Vary("Origin") // => Vary: Origin
  3. c.Vary("User-Agent") // => Vary: Origin, User-Agent
  4. // No duplicates
  5. c.Vary("Origin") // => Vary: Origin, User-Agent
  6. c.Vary("Accept-Encoding", "Accept")
  7. // => Vary: Origin, User-Agent, Accept-Encoding, Accept
  8. })

Write

Appends any input to the HTTP body response.

  1. c.Write(body ...interface{})
  1. app.Get("/", func(c *fiber.Ctx) {
  2. c.Write("Hello, ") // => "Hello, "
  3. c.Write([]byte("World! ")) // => "Hello, World! "
  4. c.Write(123) // => "Hello, World! 123"
  5. })

XHR

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).

  1. c.XHR() bool
  1. // X-Requested-With: XMLHttpRequest
  2. app.Get("/", func(c *fiber.Ctx) {
  3. c.XHR() // true
  4. })