Links
🧠

Context

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.

Accepts

Checks, if the specified extensions or content types are acceptable.
Based on the request’s Accept HTTP header.
Signature
func (c *Ctx) Accepts(offers ...string) string
func (c *Ctx) AcceptsCharsets(offers ...string) string
func (c *Ctx) AcceptsEncodings(offers ...string) string
func (c *Ctx) AcceptsLanguages(offers ...string) string
Example
// Accept: text/*, application/json
​
app.Get("/", func(c *fiber.Ctx) error {
c.Accepts("html") // "html"
c.Accepts("text/html") // "text/html"
c.Accepts("json", "text") // "json"
c.Accepts("application/json") // "application/json"
c.Accepts("image/png") // ""
c.Accepts("png") // ""
// ...
})
Fiber provides similar functions for the other accept headers.
// Accept-Charset: utf-8, iso-8859-1;q=0.2
// Accept-Encoding: gzip, compress;q=0.2
// Accept-Language: en;q=0.8, nl, ru
​
app.Get("/", func(c *fiber.Ctx) error {
c.AcceptsCharsets("utf-16", "iso-8859-1")
// "iso-8859-1"
​
c.AcceptsEncodings("compress", "br")
// "compress"
​
c.AcceptsLanguages("pt", "nl", "ru")
// "nl"
// ...
})

AllParams

Params is used to get all route parameters. Using Params method to get params.
Signature
func (c *Ctx) AllParams() map[string]string
Example
// GET http://example.com/user/fenny
app.Get("/user/:name", func(c *fiber.Ctx) error {
c.AllParams() // "{"name": "fenny"}"
​
// ...
})
​
// GET http://example.com/user/fenny/123
app.Get("/user/*", func(c *fiber.Ctx) error {
c.AllParams() // "{"*1": "fenny/123"}"
​
// ...
})

App

Returns the *App reference so you could easily access all application settings.
Signature
func (c *Ctx) App() *App
Example
app.Get("/stack", func(c *fiber.Ctx) error {
return c.JSON(c.App().Stack())
})

Append

Appends the specified value to the HTTP response header field.
If the header is not already set, it creates the header with the specified value.
Signature
func (c *Ctx) Append(field string, values ...string)
Example
app.Get("/", func(c *fiber.Ctx) error {
c.Append("Link", "http://google.com", "http://localhost")
// => Link: http://localhost, http://google.com
​
c.Append("Link", "Test")
// => Link: http://localhost, http://google.com, Test
​
// ...
})

Attachment

Sets the HTTP response Content-Disposition header field to attachment.
Signature
func (c *Ctx) Attachment(filename ...string)
Example
app.Get("/", func(c *fiber.Ctx) error {
c.Attachment()
// => Content-Disposition: attachment
​
c.Attachment("./upload/images/logo.png")
// => Content-Disposition: attachment; filename="logo.png"
// => Content-Type: image/png
​
// ...
})

BaseURL

Returns the base URL (protocol + host) as a string.
Signature
func (c *Ctx) BaseURL() string
Example
// GET https://example.com/page#chapter-1
​
app.Get("/", func(c *fiber.Ctx) error {
c.BaseURL() // https://example.com
// ...
})

Bind

Add vars to default view var map binding to template engine. Variables are read by the Render method and may be overwritten.
Signature
func (c *Ctx) Bind(vars Map) error
Example
app.Use(func(c *fiber.Ctx) error {
c.Bind(fiber.Map{
"Title": "Hello, World!",
})
})
​
app.Get("/", func(c *fiber.Ctx) error {
return c.Render("xxx.tmpl", fiber.Map{}) // Render will use Title variable
})

Body

Returns the raw request body.
Signature
func (c *Ctx) Body() []byte
Example
// curl -X POST http://localhost:8080 -d user=john
​
app.Post("/", func(c *fiber.Ctx) error {
// Get raw body from POST request:
return c.Send(c.Body()) // []byte("user=john")
})
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.
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".
content-type
struct tag
application/x-www-form-urlencoded
form
multipart/form-data
form
application/json
json
application/xml
xml
text/xml
xml
Signature
func (c *Ctx) BodyParser(out interface{}) error
Example
// Field names should start with an uppercase letter
type Person struct {
Name string `json:"name" xml:"name" form:"name"`
Pass string `json:"pass" xml:"pass" form:"pass"`
}
​
app.Post("/", func(c *fiber.Ctx) error {
p := new(Person)
​
if err := c.BodyParser(p); err != nil {
return err
}
​
log.Println(p.Name) // john
log.Println(p.Pass) // doe
​
// ...
})
​
// Run tests with the following curl commands
​
// curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"pass\":\"doe\"}" localhost:3000
​
// curl -X POST -H "Content-Type: application/xml" --data "<login><name>john</name><pass>doe</pass></login>" localhost:3000
​
// curl -X POST -H "Content-Type: application/x-www-form-urlencoded" --data "name=john&pass=doe" localhost:3000
​
// curl -X POST -F name=john -F pass=doe http://localhost:3000
​
// curl -X POST "http://localhost:3000/?name=john&pass=doe"
Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead. Read more...​

ClearCookie

Expire a client cookie (or all cookies if left empty)
Signature
func (c *Ctx) ClearCookie(key ...string)
Example
app.Get("/", func(c *fiber.Ctx) error {
// Clears all cookies:
c.ClearCookie()
​
// Expire specific cookie by name:
c.ClearCookie("user")
​
// Expire multiple cookies by names:
c.ClearCookie("token", "session", "track_id", "version")
// ...
})
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.
Example
app.Get("/set", func(c *fiber.Ctx) error {
c.Cookie(&fiber.Cookie{
Name: "token",
Value: "randomvalue",
Expires: time.Now().Add(24 * time.Hour),
HTTPOnly: true,
SameSite: "lax",
})
​
// ...
})
​
app.Get("/delete", func(c *fiber.Ctx) error {
c.Cookie(&fiber.Cookie{
Name: "token",
// Set expiry date to the past
Expires: time.Now().Add(-(time.Hour * 2)),
HTTPOnly: true,
SameSite: "lax",
})
​
// ...
})

ClientHelloInfo

ClientHelloInfo contains information from a ClientHello message in order to guide application logic in the GetCertificate and GetConfigForClient callbacks. You can refer to the ClientHelloInfo struct documentation for more information on the returned struct.
Signature
func (c *Ctx) ClientHelloInfo() *tls.ClientHelloInfo
Example
// GET http://example.com/hello
app.Get("/hello", func(c *fiber.Ctx) error {
chi := c.ClientHelloInfo()
// ...
})

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.
Signature
func (c *Ctx) Context() *fasthttp.RequestCtx
Please read the Fasthttp Documentation for more information.
Set cookie
Signature
func (c *Ctx) Cookie(cookie *Cookie)
type Cookie struct {
Name string `json:"name"`
Value string `json:"value"`
Path string `json:"path"`
Domain string `json:"domain"`
MaxAge int `json:"max_age"`
Expires time.Time `json:"expires"`
Secure bool `json:"secure"`
HTTPOnly bool `json:"http_only"`
SameSite string `json:"same_site"`
SessionOnly bool `json:"session_only"`
}
Example
app.Get("/", func(c *fiber.Ctx) error {
// Create cookie
cookie := new(fiber.Cookie)
cookie.Name = "john"
cookie.Value = "doe"
cookie.Expires = time.Now().Add(24 * time.Hour)
​
// Set cookie
c.Cookie(cookie)
// ...
})

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
func (c *Ctx) Cookies(key string, defaultValue ...string) string
Example
app.Get("/", func(c *fiber.Ctx) error {
// Get cookie by key:
c.Cookies("name") // "john"
c.Cookies("empty", "doe") // "doe"
// ...
})
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.
Signature
func (c *Ctx) Download(file string, filename ...string) error
Example
app.Get("/", func(c *fiber.Ctx) error {
return c.Download("./files/report-12345.pdf");
// => Download report-12345.pdf
​
return c.Download("./files/report-12345.pdf", "report.pdf");
// => Download report.pdf
})

Format

Performs content-negotiation on the Accept 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.
Signature
func (c *Ctx) Format(body interface{}) error
Example
app.Get("/", func(c *fiber.Ctx) error {
// Accept: text/plain
c.Format("Hello, World!")
// => Hello, World!
​
// Accept: text/html
c.Format("Hello, World!")
// => <p>Hello, World!</p>
​
// Accept: application/json
c.Format("Hello, World!")
// => "Hello, World!"
// ..
})

FormFile

MultipartForm files can be retrieved by name, the first file from the given key is returned.
Signature
func (c *Ctx) FormFile(key string) (*multipart.FileHeader, error)
Example
app.Post("/", func(c *fiber.Ctx) error {
// Get first file from form field "document":
file, err := c.FormFile("document")
​
// Save file to root directory:
return c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
})

FormValue

Any form values can be retrieved by name, the first value from the given key is returned.
Signature
func (c *Ctx) FormValue(key string, defaultValue ...string) string
Example
app.Post("/", func(c *fiber.Ctx) error {
// Get first value from form field "name":
c.FormValue("name")
// => "john" or "" if not exist
​
// ..
})
Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead. Read more...​

Fresh

Signature
func (c *Ctx) Fresh() bool

Get

Returns the HTTP request header specified by the field.
The match is case-insensitive.
Signature
func (c *Ctx) Get(key string, defaultValue ...string) string
Example
app.Get("/", func(c *fiber.Ctx) error {
c.Get("Content-Type") // "text/plain"
c.Get("CoNtEnT-TypE") // "text/plain"
c.Get("something", "john") // "john"
// ..
})
Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead. Read more...​

GetReqHeaders

Returns the HTTP request headers.
Signature
func (c *Ctx) GetReqHeaders() map[string]string

GetRespHeader

Returns the HTTP response header specified by the field.
The match is case-insensitive.
Signature
func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string
Example
app.Get("/", func(c *fiber.Ctx) error {
c.GetRespHeader("X-Request-Id") // "8d7ad5e3-aaf3-450b-a241-2beb887efd54"
c.GetRespHeader("Content-Type") // "text/plain"
c.GetRespHeader("something", "john") // "john"
// ..
})
Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead. Read more...​

GetRespHeaders

Returns the HTTP response headers.
Signature
func (c *Ctx) GetRespHeaders() map[string]string

GetRouteURL

Generates URLs to named routes, with parameters. URLs are relative, for example: "/user/1831"
Signature
func (c *Ctx) GetRouteURL(routeName string, params Map) (string, error)
Example
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Home page")
}).Name("home")
​
app.Get("/user/:id", func(c *fiber.Ctx) error {
return c.SendString(c.Params("id"))
}).Name("user.show")
​
app.Get("/test", func(c *fiber.Ctx) error {
location, _ := c.GetRouteURL("user.show", fiber.Map{"id": 1})
return c.SendString(location)
})
​
// /test returns "/user/1"

Hostname

Returns the hostname derived from the Host HTTP header.
Signature
func (c *Ctx) Hostname() string
Example
// GET http://google.com/search
​
app.Get("/", func(c *fiber.Ctx) error {
c.Hostname() // "google.com"
​
// ...
})
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.
Signature
func (c *Ctx) IP() string
Example
app.Get("/", func(c *fiber.Ctx) error {
c.IP() // "127.0.0.1"
​
// ...
})

IPs

Returns an array of IP addresses specified in the X-Forwarded-For request header.
Signature
func (c *Ctx) IPs() []string
Example
// X-Forwarded-For: proxy1, 127.0.0.1, proxy3
​
app.Get("/", func(c *fiber.Ctx) error {
c.IPs() // ["proxy1", "127.0.0.1", "proxy3"]
​
// ...
})

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

IsFromLocal

Returns true if request came from localhost
Signature
func (c *Ctx) IsFromLocal() bool {
Example
app.Get("/", func(c *fiber.Ctx) error {
// If request came from localhost, return true else return false
c.isFromLocal()
​
// ...
})

JSON

Converts any interface or string to JSON using the goccy/go-json package.
JSON also sets the content header to application/json.
Signature
func (c *Ctx) JSON(data interface{}) error
Example
type SomeStruct struct {
Name string
Age uint8
}
​
app.Get("/json", func(c *fiber.Ctx) error {
// Create data struct:
data := SomeStruct{
Name: "Grame",
Age: 20,
}
​
return c.JSON(data)
// => Content-Type: application/json
// => "{"Name": "Grame", "Age": 20}"
​
return c.JSON(fiber.Map{
"name": "Grame",
"age": 20,
})
// => Content-Type: application/json
// => "{"name": "Grame", "age": 20}"
})

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.
Signature
func (c *Ctx) JSONP(data interface{}, callback ...string) error
Example
type SomeStruct struct {
name string
age uint8
}
​
app.Get("/", func(c *fiber.Ctx) error {
// Create data struct:
data := SomeStruct{
name: "Grame",
age: 20,
}
​
return c.JSONP(data)
// => callback({"name": "Grame", "age": 20})
​
return c.JSONP(data, "customFunc")
// => customFunc({"name": "Grame", "age": 20})
})
Joins the links followed by the property to populate the response’s Link HTTP header field.
Signature
func (c *Ctx) Links(link ...string)
Example
app.Get("/", func(c *fiber.Ctx) error {
c.Links(
"http://api.example.com/users?page=2", "next",
"http://api.example.com/users?page=5", "last",
)
// Link: <http://api.example.com/users?page=2>; rel="next",
// <http://api.example.com/users?page=5>; rel="last"
​
// ...
})

Locals

A method that stores variables scoped to the request and, therefore, are available only to the routes that match the request.
This is useful if you want to pass some specific data to the next middleware.
Signature
func (c *Ctx) Locals(key string, value ...interface{}) interface{}
Example
app.Use(func(c *fiber.Ctx) error {
c.Locals("user", "admin")
return c.Next()
})
​
app.Get("/admin", func(c *fiber.Ctx) error {
if c.Locals("user") == "admin" {
return c.Status(fiber.StatusOK).SendString("Welcome, admin!")
}
return c.SendStatus(fiber.StatusForbidden)
​
})

Location

Sets the response Location HTTP header to the specified path parameter.
Signature
func (c *Ctx) Location(path string)
Example
app.Post("/", func(c *fiber.Ctx) error {
c.Location("http://example.com")
​
c.Location("/foo/bar")
return nil
})

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.
Signature
func (c *Ctx) Method(override ...string) string
Example
app.Post("/", func(c *fiber.Ctx) error {
c.Method() // "POST"
​
c.Method("GET")
c.Method() // GET
​
// ...
})

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.
Signature
func (c *Ctx) MultipartForm() (*multipart.Form, error)
Example
app.Post("/", func(c *fiber.Ctx) error {
// Parse the multipart form:
if form, err := c.MultipartForm(); err == nil {
// => *multipart.Form
​
if token := form.Value["token"]; len(token) > 0 {
// Get key value:
fmt.Println(token[0])
}
​
// Get all files from "documents" key:
files := form.File["documents"]
// => []*multipart.FileHeader
​
// Loop through files:
for _, file := range files {
fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0])
// => "tutorial.pdf" 360641 "application/pdf"
​
// Save the files to disk:
if err := c.SaveFile(file, fmt.Sprintf("./%s", file.Filename)); err != nil {
return err
}
}
}
​
return err
})

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.
Signature
func (c *Ctx) Next() error
Example
app.Get("/", func(c *fiber.Ctx) error {
fmt.Println("1st route!")
return c.Next()
})
​
app.Get("*", func(c *fiber.Ctx) error {
fmt.Println("2nd route!")
return c.Next()
})
​
app.Get("/", func(c *fiber.Ctx) error {
fmt.Println("3rd route!")
return c.SendString("Hello, World!")
})

OriginalURL

Returns the original request URL.
Signature
func (c *Ctx) OriginalURL() string
Example
// GET http://example.com/search?q=something
​
app.Get("/", func(c *fiber.Ctx) error {
c.OriginalURL() // "/search?q=something"
​
// ...
})
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.
Signature
func (c *Ctx) Params(key string, defaultValue ...string) string
Example
// GET http://example.com/user/fenny
app.Get("/user/:name", func(c *fiber.Ctx) error {
c.Params("name") // "fenny"