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. func (c *Ctx) Accepts(offers ...string) string
  2. func (c *Ctx) AcceptsCharsets(offers ...string) string
  3. func (c *Ctx) AcceptsEncodings(offers ...string) string
  4. func (c *Ctx) AcceptsLanguages(offers ...string) string
  1. // Accept: text/*, application/json
  2. app.Get("/", func(c *fiber.Ctx) error {
  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. // ...
  10. })

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) error {
  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. // ...
  12. })

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. func (c *Ctx) Append(field string, values ...string)
  1. app.Get("/", func(c *fiber.Ctx) error {
  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. // ...
  7. })

Attachment

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

  1. func (c *Ctx) Attachment(filename ...string)
  1. app.Get("/", func(c *fiber.Ctx) error {
  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. // ...
  8. })

App

Returns the *App reference so you could easily access all application settings.

  1. func (c *Ctx) App() *App
  1. app.Get("/stack", func(c *fiber.Ctx) error {
  2. return c.JSON(c.App().Stack())
  3. })

BaseURL

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

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

Body

Returns the raw request body.

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

Returned value is only valid within the handler. Do not store any references.
Make copies or use the
Immutable setting instead. Read more…

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. func (c *Ctx) 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"`
  4. Pass string `json:"pass" xml:"pass" form:"pass"`
  5. }
  6. app.Post("/", func(c *fiber.Ctx) error {
  7. p := new(Person)
  8. if err := c.BodyParser(p); err != nil {
  9. return err
  10. }
  11. log.Println(p.Name) // john
  12. log.Println(p.Pass) // doe
  13. // ...
  14. })
  15. // Run tests with the following curl commands
  16. // curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"pass\":\"doe\"}" localhost:3000
  17. // curl -X POST -H "Content-Type: application/xml" --data "<login><name>john</name><pass>doe</pass></login>" localhost:3000
  18. // curl -X POST -H "Content-Type: application/x-www-form-urlencoded" --data "name=john&pass=doe" localhost:3000
  19. // curl -X POST -F name=john -F pass=doe http://localhost:3000
  20. // curl -X POST "http://localhost:3000/?name=john&pass=doe"

ClearCookie

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

  1. func (c *Ctx) ClearCookie(key ...string)
  1. app.Get("/", func(c *fiber.Ctx) error {
  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. // ...
  9. })

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.

  1. app.Get("/set", func(c *fiber.Ctx) error {
  2. c.Cookie(&fiber.Cookie{
  3. Name: "token",
  4. Value: "randomvalue",
  5. Expires: time.Now().Add(24 * time.Hour),
  6. HTTPOnly: true,
  7. SameSite: "lax",
  8. })
  9. // ...
  10. })
  11. app.Get("/delete", func(c *fiber.Ctx) error {
  12. c.Cookie(&fiber.Cookie{
  13. Name: "token",
  14. // Set expiry date to the past
  15. Expires: time.Now().Add(-(time.Hour * 2)),
  16. HTTPOnly: true,
  17. SameSite: "lax",
  18. })
  19. // ...
  20. })

Context

Returns *fasthttp.RequestCtx that is compatible with the context.Context interface that requires a deadline, a cancellation signal, and other values across API boundaries.

  1. func (c *Ctx) Context() *fasthttp.RequestCtx

Please read the Fasthttp Documentation for more information.

Cookie

Set cookie

  1. func (c *Ctx) Cookie(cookie *Cookie)
  1. type Cookie struct {
  2. Name string `json:"name"`
  3. Value string `json:"value"`
  4. Path string `json:"path"`
  5. Domain string `json:"domain"`
  6. MaxAge int `json:"max_age"`
  7. Expires time.Time `json:"expires"`
  8. Secure bool `json:"secure"`
  9. HTTPOnly bool `json:"http_only"`
  10. SameSite string `json:"same_site"`
  11. }
  1. app.Get("/", func(c *fiber.Ctx) error {
  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. // ...
  10. })

Cookies

Get cookie value by key, you could pass an optional default value that will be returned if the cookie key does not exist.

Signatures

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

Returned value is only valid within the handler. Do not store any references.
Make copies or use the
Immutable setting instead. Read more…

Download

Transfers the file from path as an attachment.

Typically, browsers will prompt the user to download. By default, the Content-Disposition header filename= parameter is the file path (this typically appears in the browser dialog).

Override this default with the filename parameter.

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

Request

Request return the *fasthttp.Request pointer

Signature

  1. func (c *Ctx) Request() *fasthttp.Request

Example

  1. app.Get("/", func(c *fiber.Ctx) error {
  2. c.Request().Header.Method()
  3. // => []byte("GET")
  4. })

Response

Request return the *fasthttp.Response pointer

Signature

  1. func (c *Ctx) Response() *fasthttp.Response

Example

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

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. func (c *Ctx) Format(body interface{}) error
  1. app.Get("/", func(c *fiber.Ctx) error {
  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. // ..
  12. })

FormFile

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

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

FormValue

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

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

Returned value is only valid within the handler. Do not store any references.
Make copies or use the
Immutable setting instead. Read more…

Fresh

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

  1. func (c *Ctx) Fresh() bool

Get

Returns the HTTP request header specified by the field.

The match is case-insensitive.

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

Returned value is only valid within the handler. Do not store any references.
Make copies or use the
Immutable setting instead. Read more…

Hostname

Returns the hostname derived from the Host HTTP header.

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

Returned value is only valid within the handler. Do not store any references.
Make copies or use the
Immutable setting instead. Read more…

IP

Returns the remote IP address of the request.

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

IPs

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

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

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. func (c *Ctx) Is(extension string) bool
  1. // Content-Type: text/html; charset=utf-8
  2. app.Get("/", func(c *fiber.Ctx) error {
  3. c.Is("html") // true
  4. c.Is(".html") // true
  5. c.Is("json") // false
  6. // ...
  7. })

JSON

Converts any interface or string to JSON using the segmentio/encoding package.

JSON also sets the content header to application/json.

  1. func (c *Ctx) JSON(data interface{}) error
  1. type SomeStruct struct {
  2. Name string
  3. Age uint8
  4. }
  5. app.Get("/json", func(c *fiber.Ctx) error {
  6. // Create data struct:
  7. data := SomeStruct{
  8. Name: "Grame",
  9. Age: 20,
  10. }
  11. return c.JSON(data)
  12. // => Content-Type: application/json
  13. // => "{"Name": "Grame", "Age": 20}"
  14. return 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. func (c *Ctx) JSONP(data interface{}, callback ...string) error
  1. type SomeStruct struct {
  2. name string
  3. age uint8
  4. }
  5. app.Get("/", func(c *fiber.Ctx) error {
  6. // Create data struct:
  7. data := SomeStruct{
  8. name: "Grame",
  9. age: 20,
  10. }
  11. return c.JSONP(data)
  12. // => callback({"name": "Grame", "age": 20})
  13. return 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. func (c *Ctx) Links(link ...string)
  1. app.Get("/", func(c *fiber.Ctx) error {
  2. c.Links(
  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. // ...
  9. })

Locals

A method that stores variables scoped to the request and, therefore, are 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. func (c *Ctx) Locals(key string, value ...interface{}) interface{}
  1. app.Use(func(c *fiber.Ctx) error {
  2. c.Locals("user", "admin")
  3. return c.Next()
  4. })
  5. app.Get("/admin", func(c *fiber.Ctx) error {
  6. if c.Locals("user") == "admin" {
  7. return c.Status(200).SendString("Welcome, admin!")
  8. }
  9. return c.SendStatus(403)
  10. })

Location

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

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

Method

Returns a string corresponding to the HTTP method of the request: GET, POST, PUT, and so on.
Optionally, you could override the method by passing a string.

  1. func (c *Ctx) Method(override ...string) string
  1. app.Post("/", func(c *fiber.Ctx) error {
  2. c.Method() // "POST"
  3. c.Method("GET")
  4. c.Method() // GET
  5. // ...
  6. })

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. func (c *Ctx) MultipartForm() (*multipart.Form, error)
  1. app.Post("/", func(c *fiber.Ctx) error {
  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. if err := c.SaveFile(file, fmt.Sprintf("./%s", file.Filename)); err != nil {
  18. return err
  19. }
  20. }
  21. }
  22. return err
  23. })

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 that will end the chaining and call the error handler.

  1. func (c *Ctx) Next() error
  1. app.Get("/", func(c *fiber.Ctx) error {
  2. fmt.Println("1st route!")
  3. return c.Next()
  4. })
  5. app.Get("*", func(c *fiber.Ctx) error {
  6. fmt.Println("2nd route!")
  7. return c.Next()
  8. })
  9. app.Get("/", func(c *fiber.Ctx) error {
  10. fmt.Println("3rd route!")
  11. return c.SendString("Hello, World!")
  12. })

OriginalURL

Returns the original request URL.

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

Returned value is only valid within the handler. Do not store any references.
Make copies or use the
Immutable setting instead. Read more…

Params

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.

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

  1. func (c *Ctx) Params(key string, defaultValue ...string) string
  1. // GET http://example.com/user/fenny
  2. app.Get("/user/:name", func(c *fiber.Ctx) error {
  3. c.Params("name") // "fenny"
  4. // ...
  5. })
  6. // GET http://example.com/user/fenny/123
  7. app.Get("/user/*", func(c *fiber.Ctx) error {
  8. c.Params("*") // "fenny/123"
  9. c.Params("*1") // "fenny/123"
  10. // ...
  11. })

Unnamed route parameters(*, +) can be fetched by the character and the counter in the route.

  1. // ROUTE: /v1/*/shop/*
  2. // GET: /v1/brand/4/shop/blue/xs
  3. c.Params("*1") // "brand/4"
  4. c.Params("*2") // "blue/xs"

For reasons of downward compatibility, the first parameter segment for the parameter character can also be accessed without the counter.

  1. app.Get("/v1/*/shop/*", func(c *fiber.Ctx) error {
  2. c.Params("*") // outputs the values of the first wildcard segment
  3. })

Returned value is only valid within the handler. Do not store any references.
Make copies or use the
Immutable setting instead. Read more…

ParamsInt

Method can be used to get an integer from the route parameters. Please note if that parameter is not in the request, zero will be returned. If the parameter is NOT a number, zero and an error will be returned

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

  1. func (c *Ctx) Params(key string) (int, error)
  1. // GET http://example.com/user/123
  2. app.Get("/user/:name", func(c *fiber.Ctx) error {
  3. id, err := c.ParamsInt("id") // int 123 and no error
  4. // ...
  5. })

This method is equivalent of using atoi with ctx.Params

Path

Contains the path part of the request URL. Optionally, you could override the path by passing a string.

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

Protocol

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

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

Query

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.

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

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

Returned value is only valid within the handler. Do not store any references.
Make copies or use the
Immutable setting instead. Read more…

QueryParser

This method is similar to BodyParser, but for query parameters.

  1. func (c *Ctx) QueryParser(out interface{}) error
  1. // Field names should start with an uppercase letter
  2. type Person struct {
  3. Name string `query:"name"`
  4. Pass string `query:"pass"`
  5. Products []string `query:"products"`
  6. }
  7. app.Get("/", func(c *fiber.Ctx) error {
  8. p := new(Person)
  9. if err := c.QueryParser(p); err != nil {
  10. return err
  11. }
  12. log.Println(p.Name) // john
  13. log.Println(p.Pass) // doe
  14. log.Println(p.Products) // [shoe, hat]
  15. // ...
  16. })
  17. // Run tests with the following curl command
  18. // curl "http://localhost:3000/?name=john&pass=doe&products=shoe,hat"

Range

A struct containing the type and a slice of ranges will be returned.

  1. func (c *Ctx) Range(size int) (Range, error)
  1. // Range: bytes=500-700, 700-900
  2. app.Get("/", func(c *fiber.Ctx) error {
  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. func (c *Ctx) Redirect(location string, status ...int) error
  1. app.Get("/coffee", func(c *fiber.Ctx) error {
  2. return c.Redirect("/teapot")
  3. })
  4. app.Get("/teapot", func(c *fiber.Ctx) error {
  5. return c.Status(fiber.StatusTeapot).Send("🍵 short and stout 🍵")
  6. })
  1. app.Get("/", func(c *fiber.Ctx) error {
  2. return c.Redirect("/foo/bar")
  3. return c.Redirect("../login")
  4. return c.Redirect("http://example.com")
  5. return c.Redirect("http://example.com", 301)
  6. })

Render

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

  1. func (c *Ctx) Render(name string, bind interface{}, layouts ...string) error

Route

Returns the matched Route struct.

  1. func (c *Ctx) Route() *Route
  1. // http://localhost:8080/hello
  2. app.Get("/hello/:name", func(c *fiber.Ctx) error {
  3. r := c.Route()
  4. fmt.Println(r.Method, r.Path, r.Params, r.Handlers)
  5. // GET /hello/:name handler [name]
  6. // ...
  7. })

Do not rely on c.Route() in middlewares before calling c.Next() - c.Route() returns the last executed route.

  1. func MyMiddleware() fiber.Handler {
  2. return func(c *fiber.Ctx) error {
  3. beforeNext := c.Route().Path // Will be '/'
  4. err := c.Next()
  5. afterNext := c.Route().Path // Will be '/hello/:name'
  6. return err
  7. }
  8. }

SaveFile

Method is used to save any multipart file to disk.

  1. func (c *Ctx) SaveFile(fh *multipart.FileHeader, path string) error
  1. app.Post("/", func(c *fiber.Ctx) error {
  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. if err := c.SaveFile(file, fmt.Sprintf("./%s", file.Filename)); err != nil {
  14. return err
  15. }
  16. }
  17. return err
  18. }
  19. })

Secure

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

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

Send

Sets the HTTP response body.

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

Fiber also provides SendString and SendStream methods for raw inputs.

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

  1. func (c *Ctx) SendString(body string) error
  2. func (c *Ctx) SendStream(stream io.Reader, size ...int) error
  1. app.Get("/", func(c *fiber.Ctx) error {
  2. return c.SendString("Hello, World!")
  3. // => "Hello, World!"
  4. return c.SendStream(bytes.NewReader([]byte("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. func (c *Ctx) SendFile(file string, compress ...bool) error
  1. app.Get("/not-found", func(c *fiber.Ctx) error {
  2. return c.SendFile("./public/404.html");
  3. // Disable compression
  4. return c.SendFile("./static/index.html", false);
  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. func (c *Ctx) SendStatus(status int) error
  1. app.Get("/not-found", func(c *fiber.Ctx) error {
  2. return c.SendStatus(415)
  3. // => 415 "Unsupported Media Type"
  4. c.SendString("Hello, World!")
  5. return c.SendStatus(415)
  6. // => 415 "Hello, World!"
  7. })

Set

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

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

SetUserContext

Sets the user specified implementation for context interface.

  1. func (c *Ctx) SetUserContext(ctx context.Context)
  1. app.Get("/", func(c *fiber.Ctx) error {
  2. ctx := context.Background()
  3. c.SetUserContext(ctx)
  4. // Here ctx could be any context implementation
  5. // ...
  6. })

Stale

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

  1. func (c *Ctx) Stale() bool

Status

Sets the HTTP status for the response.

Method is a chainable.

  1. func (c *Ctx) Status(status int) *Ctx
  1. app.Get("/fiber", func(c *fiber.Ctx) error {
  2. c.Status(200)
  3. return nil
  4. }
  5. app.Get("/hello", func(c *fiber.Ctx) error {
  6. return c.Status(400).SendString("Bad Request")
  7. }
  8. app.Get("/world", func(c *fiber.Ctx) error {
  9. return c.Status(404).SendFile("./public/gopher.png")
  10. })

Subdomains

Returns a string slice 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. func (c *Ctx) Subdomains(offset ...int) []string
  1. // Host: "tobi.ferrets.example.com"
  2. app.Get("/", func(c *fiber.Ctx) error {
  3. c.Subdomains() // ["ferrets", "tobi"]
  4. c.Subdomains(1) // ["tobi"]
  5. // ...
  6. })

Type

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

  1. func (c *Ctx) Type(ext string, charset ...string) *Ctx
  1. app.Get("/", func(c *fiber.Ctx) error {
  2. c.Type(".html") // => "text/html"
  3. c.Type("html") // => "text/html"
  4. c.Type("png") // => "image/png"
  5. c.Type("json", "utf-8") // => "application/json; charset=utf-8"
  6. // ...
  7. })

UserContext

UserContext returns a context implementation that was set by user earlier or returns a non-nil, empty context, if it was not set earlier.

  1. func (c *Ctx) UserContext() context.Context
  1. app.Get("/", func(c *fiber.Ctx) error {
  2. ctx := c.UserContext()
  3. // ctx is context implementation set by user
  4. // ...
  5. })

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. func (c *Ctx) Vary(fields ...string)
  1. app.Get("/", func(c *fiber.Ctx) error {
  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. // ...
  9. })

Write

Write adopts the Writer interface

  1. func (c *Ctx) Write(p []byte) (n int, err error)
  1. app.Get("/", func(c *fiber.Ctx) error {
  2. c.Write([]byte("Hello, World!")) // => "Hello, World!"
  3. fmt.Fprintf(c, "%s\n", "Hello, World!") // "Hello, World!Hello, World!"
  4. })

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. func (c *Ctx) XHR() bool
  1. // X-Requested-With: XMLHttpRequest
  2. app.Get("/", func(c *fiber.Ctx) error {
  3. c.XHR() // true
  4. // ...
  5. })