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. |
Checks, if the specified extensions or content types are acceptable.
{% hint style="info" %} Based on the request’s Accept HTTP header. {% endhint %}
{% code title="Signature" %}
c.Accepts(types ...string) string
c.AcceptsCharsets(charsets ...string) string
c.AcceptsEncodings(encodings ...string) string
c.AcceptsLanguages(langs ...string) string
{% endcode %}
{% code title="Example" %}
// Accept: text/*, application/json
app.Get("/", func(c *fiber.Ctx) {
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") // ""
})
{% endcode %}
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) {
c.AcceptsCharsets("utf-16", "iso-8859-1")
// "iso-8859-1"
c.AcceptsEncodings("compress", "br")
// "compress"
c.AcceptsLanguages("pt", "nl", "ru")
// "nl"
})
Appends the specified value to the HTTP response header field.
{% hint style="warning" %} If the header is not already set, it creates the header with the specified value. {% endhint %}
{% code title="Signature" %}
c.Append(field, values ...string)
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
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
})
{% endcode %}
Sets the HTTP response Content-Disposition header field to attachment
.
{% code title="Signature" %}
c.Attachment(file ...string)
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.Attachment()
// => Content-Disposition: attachment
c.Attachment("./upload/images/logo.png")
// => Content-Disposition: attachment; filename="logo.png"
// => Content-Type: image/png
})
{% endcode %}
Returns base URL (protocol + host) as a string
.
{% code title="Signature" %}
c.BaseURL() string
{% endcode %}
{% code title="Example" %}
// GET https://example.com/page#chapter-1
app.Get("/", func(c *fiber.Ctx) {
c.BaseURL() // https://example.com
})
{% endcode %}
Contains the raw body submitted in a POST request.
{% code title="Signature" %}
c.Body() string
{% endcode %}
{% code title="Example" %}
// curl -X POST http://localhost:8080 -d user=john
app.Post("/", func(c *fiber.Ctx) {
// Get raw body from POST request:
c.Body() // user=john
})
{% endcode %}
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
{% code title="Signature" %}
c.BodyParser(out interface{}) error
{% endcode %}
{% code title="Example" %}
// Field names should start with an uppercase letter
type Person struct {
Name string `json:"name" xml:"name" form:"name" query:"name"`
Pass string `json:"pass" xml:"pass" form:"pass" query:"pass"`
}
app.Post("/", func(c *fiber.Ctx) {
p := new(Person)
if err := c.BodyParser(p); err != nil {
log.Fatal(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"
{% endcode %}
Expire a client cookie (or all cookies if left empty)
{% code title="Signature" %}
c.ClearCookie(key ...string)
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
// 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")
})
{% endcode %}
Set cookie
Signature
c.Cookie(*Cookie)
type Cookie struct {
Name string
Value string
Path string
Domain string
MaxAge int
Expires time.Time
Secure bool
HTTPOnly bool
SameSite string // lax, strict, none
}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
// 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)
})
{% endcode %}
Get cookie value by key.
Signatures
c.Cookies(key string) string
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
// Get cookie by key:
c.Cookies("name") // "john"
})
{% endcode %}
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.
{% code title="Signature" %}
c.Download(path, filename ...string)
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.Download("./files/report-12345.pdf")
// => Download report-12345.pdf
c.Download("./files/report-12345.pdf", "report.pdf")
// => Download report.pdf
})
{% endcode %}
You can still access and use all Fasthttp methods and properties.
Signature
{% hint style="info" %} Please read the Fasthttp Documentation for more information. {% endhint %}
Example
app.Get("/", func(c *fiber.Ctx) {
c.Fasthttp.Request.Header.Method()
// => []byte("GET")
c.Fasthttp.Response.Write([]byte("Hello, World!"))
// => "Hello, World!"
})
This contains the error information that thrown by a panic or passed via the Next(err)
method.
{% code title="Signature" %}
c.Error() error
{% endcode %}
{% code title="Example" %}
func main() {
app := fiber.New()
app.Post("/api/register", func (c *fiber.Ctx) {
if err := c.JSON(&User); err != nil {
c.Next(err)
}
})
app.Get("/api/user", func (c *fiber.Ctx) {
if err := c.JSON(&User); err != nil {
c.Next(err)
}
})
app.Put("/api/update", func (c *fiber.Ctx) {
if err := c.JSON(&User); err != nil {
c.Next(err)
}
})
app.Use("/api", func(c *fiber.Ctx) {
c.Set("Content-Type", "application/json")
c.Status(fiber.StatusInternalServerError).Send(c.Error())
})
app.Listen(":1337")
}
{% endcode %}
Performs content-negotiation on the Accept HTTP header. It uses Accepts to select a proper format.
{% hint style="info" %} If the header is not specified or there is no proper format, text/plain is used. {% endhint %}
{% code title="Signature" %}
c.Format(body interface{})
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
// 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!"
})
{% endcode %}
MultipartForm files can be retrieved by name, the first file from the given key is returned.
{% code title="Signature" %}
c.FormFile(name string) (*multipart.FileHeader, error)
{% endcode %}
{% code title="Example" %}
app.Post("/", func(c *fiber.Ctx) {
// Get first file from form field "document":
file, err := c.FormFile("document")
// Check for errors:
if err == nil {
// Save file to root directory:
c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
}
})
{% endcode %}
Any form values can be retrieved by name, the first value from the given key is returned.
{% code title="Signature" %}
c.FormValue(name string) string
{% endcode %}
{% code title="Example" %}
app.Post("/", func(c *fiber.Ctx) {
// Get first value from form field "name":
c.FormValue("name")
// => "john" or "" if not exist
})
{% endcode %}
https://expressjs.com/en/4x/api.html#req.fresh
{% hint style="info" %} Not implemented yet, pull requests are welcome! {% endhint %}
Returns the HTTP request header specified by field.
{% hint style="success" %} The match is case-insensitive. {% endhint %}
{% code title="Signature" %}
c.Get(field string) string
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.Get("Content-Type") // "text/plain"
c.Get("CoNtEnT-TypE") // "text/plain"
c.Get("something") // ""
})
{% endcode %}
Contains the hostname derived from the Host HTTP header.
{% code title="Signature" %}
c.Hostname() string
{% endcode %}
{% code title="Example" %}
// GET http://google.com/search
app.Get("/", func(c *fiber.Ctx) {
c.Hostname() // "google.com"
})
{% endcode %}
Returns the remote IP address of the request.
{% code title="Signature" %}
c.IP() string
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.IP() // "127.0.0.1"
})
{% endcode %}
Returns an array of IP addresses specified in the X-Forwarded-For request header.
{% code title="Signature" %}
c.IPs() []string
{% endcode %}
{% code title="Example" %}
// X-Forwarded-For: proxy1, 127.0.0.1, proxy3
app.Get("/", func(c *fiber.Ctx) {
c.IPs() // ["proxy1", "127.0.0.1", "proxy3"]
})
{% endcode %}
Returns the matching content type, if the incoming request’s Content-Type HTTP header field matches the MIME type specified by the type parameter.
{% hint style="info" %} If the request has no body, it returns false. {% endhint %}
{% code title="Signature" %}
c.Is(t string) bool
{% endcode %}
{% code title="Example" %}
// Content-Type: text/html; charset=utf-8
app.Get("/", func(c *fiber.Ctx) {
c.Is("html") // true
c.Is(".html") // true
c.Is("json") // false
})
{% endcode %}
Converts any interface or string to JSON using Jsoniter.
{% hint style="info" %} JSON also sets the content header to application/json. {% endhint %}
{% code title="Signature" %}
c.JSON(v interface{}) error
{% endcode %}
{% code title="Example" %}
type SomeStruct struct {
Name string
Age uint8
}
app.Get("/json", func(c *fiber.Ctx) {
// Create data struct:
data := SomeStruct{
Name: "Grame",
Age: 20,
}
c.JSON(data)
// => Content-Type: application/json
// => "{"Name": "Grame", "Age": 20}"
c.JSON(fiber.Map{
"name": "Grame",
"age": 20,
})
// => Content-Type: application/json
// => "{"name": "Grame", "age": 20}"
})
{% endcode %}
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.
{% code title="Signature" %}
c.JSONP(v interface{}, callback ...string) error
{% endcode %}
{% code title="Example" %}
type SomeStruct struct {
name string
age uint8
}
app.Get("/", func(c *fiber.Ctx) {
// Create data struct:
data := SomeStruct{
name: "Grame",
age: 20,
}
c.JSONP(data)
// => callback({"name": "Grame", "age": 20})
c.JSONP(data, "customFunc")
// => customFunc({"name": "Grame", "age": 20})
})
{% endcode %}
Joins the links followed by the property to populate the response’s Link HTTP header field.
{% code title="Signature" %}
c.Links(link ...string)
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.Link(
"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"
})
{% endcode %}
Method that stores string variables scoped to the request and therefore available only to the routes that match the request.
{% hint style="success" %} This is useful, if you want to pass some specific data to the next middleware. {% endhint %}
{% code title="Signature" %}
c.Locals(key string, value ...interface{}) interface{}
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.Locals("user", "admin")
c.Next()
})
app.Get("/admin", func(c *fiber.Ctx) {
if c.Locals("user") == "admin" {
c.Status(fiber.StatusOK).Send("Welcome, admin!")
} else {
c.SendStatus(fiber.StatusForbidden)
// => 403 Forbidden
}
})
{% endcode %}
Sets the response Location HTTP header to the specified path parameter.
{% code title="Signature" %}
c.Location(path string)
{% endcode %}
{% code title="Example" %}
app.Post("/", func(c *fiber.Ctx) {
c.Location("http://example.com")
c.Location("/foo/bar")
})
{% endcode %}
Contains a string corresponding to the HTTP method of the request: GET
, POST
, PUT
and so on.
{% code title="Signature" %}
c.Method() string
{% endcode %}
{% code title="Example" %}
app.Post("/", func(c *fiber.Ctx) {
c.Method() // "POST"
})
{% endcode %}
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.
{% code title="Signature" %}
c.MultipartForm() (*multipart.Form, error)
{% endcode %}
{% code title="Example" %}
app.Post("/", func(c *fiber.Ctx) {
// 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:
c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
}
}
})
{% endcode %}
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.
{% code title="Signature" %}
c.Next(err ...error)
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
fmt.Println("1st route!")
c.Next()
})
app.Get("*", func(c *fiber.Ctx) {
fmt.Println("2nd route!")
c.Next(fmt.Errorf("Some error"))
})
app.Get("/", func(c *fiber.Ctx) {
fmt.Println(c.Error()) // => "Some error"
fmt.Println("3rd route!")
c.Send("Hello, World!")
})
{% endcode %}
Contains the original request URL.
{% code title="Signature" %}
c.OriginalURL() string
{% endcode %}
{% code title="Example" %}
// GET http://example.com/search?q=something
app.Get("/", func(c *fiber.Ctx) {
c.OriginalURL() // "/search?q=something"
})
{% endcode %}
Method can be used to get the route parameters.
{% hint style="info" %}
Defaults to empty string (""
), if the param doesn't exist.
{% endhint %}
{% code title="Signature" %}
c.Params(param string) string
{% endcode %}
{% code title="Example" %}
// GET http://example.com/user/fenny
app.Get("/user/:name", func(c *fiber.Ctx) {
c.Params("name") // "fenny"
})
{% endcode %}
Contains the path part of the request URL.
{% code title="Signature" %}
c.Path() string
{% endcode %}
{% code title="Example" %}
// GET http://example.com/users?sort=desc
app.Get("/users", func(c *fiber.Ctx) {
c.Path() // "/users"
})
{% endcode %}
Contains the request protocol string: http
or https
for TLS requests.
{% code title="Signature" %}
c.Protocol() string
{% endcode %}
{% code title="Example" %}
// GET http://example.com
app.Get("/", func(c *fiber.Ctx) {
c.Protocol() // "http"
})
{% endcode %}
This property is an object containing a property for each query string parameter in the route.
{% hint style="info" %} If there is no query string, it returns an empty string. {% endhint %}
{% code title="Signature" %}
c.Query(parameter string) string
{% endcode %}
{% code title="Example" %}
// GET http://example.com/shoes?order=desc&brand=nike
app.Get("/", func(c *fiber.Ctx) {
c.Query("order") // "desc"
c.Query("brand") // "nike"
})
{% endcode %}
An struct containg the type and a slice of ranges will be returned.
{% code title="Signature" %}
c.Range(int size)
{% endcode %}
{% code title="Example" %}
// Range: bytes=500-700, 700-900
app.Get("/", func(c *fiber.Ctx) {
b := c.Range(1000)
if b.Type == "bytes" {
for r := range r.Ranges {
fmt.Println(r)
// [500, 700]
}
}
})
{% endcode %}
Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code.
{% hint style="info" %} If not specified, status defaults to 302 Found. {% endhint %}
{% code title="Signature" %}
c.Redirect(path string, status ...int)
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.Redirect("/foo/bar")
c.Redirect("../login")
c.Redirect("http://example.com")
c.Redirect("http://example.com", 301)
})
{% endcode %}
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.
{% code title="Signature" %}
c.Render(file string, data interface{}) error
{% endcode %}
Contains the matched Route struct.
{% code title="Signature" %}
c.Route() *Route
{% endcode %}
{% code title="Example" %}
// http://localhost:8080/hello
app.Get("/hello", func(c *fiber.Ctx) {
r := c.Route()
fmt.Println(r.Method, r.Path, r.Params, r.Regexp, r.Handler)
})
app.Post("/:api?", func(c *fiber.Ctx) {
c.Route()
// => {GET /hello [] nil 0x7b49e0}
})
{% endcode %}
Method is used to save any multipart file to disk.
{% code title="Signature" %}
c.SaveFile(fh *multipart.FileHeader, path string)
{% endcode %}
{% code title="Example" %}
app.Post("/", func(c *fiber.Ctx) {
// Parse the multipart form:
if form, err := c.MultipartForm(); err == nil {
// => *multipart.Form
// 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:
c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
}
}
})
{% endcode %}
A boolean property, that is true
, if a TLS connection is established.
{% code title="Signature" %}
c.Secure() bool
{% endcode %}
{% code title="Example" %}
// Secure() method is equivalent to:
c.Protocol() == "https"
{% endcode %}
Sets the HTTP response body. The Send body can be of any type.
{% hint style="warning" %} Send doesn't append like the Write method. {% endhint %}
{% code title="Signature" %}
c.Send(body ...interface{})
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.Send("Hello, World!") // => "Hello, World!"
c.Send([]byte("Hello, World!")) // => "Hello, World!"
c.Send(123) // => 123
})
{% endcode %}
Fiber also provides SendBytes
& SendString
methods for raw inputs.
{% hint style="success" %} Use this, if you don't need type assertion, recommended for faster performance. {% endhint %}
{% code title="Signature" %}
c.SendBytes(b []byte)
c.SendString(s string)
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.SendByte([]byte("Hello, World!"))
// => "Hello, World!"
c.SendString("Hello, World!")
// => "Hello, World!"
})
{% endcode %}
Transfers the file from the given path. Sets the Content-Type response HTTP header field based on the filenames extension.
{% hint style="warning" %} Method use gzipping by default, set it to true to disable. {% endhint %}
{% code title="Signature" %}
c.SendFile(path string, gzip ...bool)
{% endcode %}
{% code title="Example" %}
app.Get("/not-found", func(c *fiber.Ctx) {
c.SendFile("./public/404.html")
// Disable gzipping:
c.SendFile("./static/index.html", true)
})
{% endcode %}
Sets the status code and the correct status message in the body, if the response body is empty.
{% hint style="success" %} You can find all used status codes and messages here. {% endhint %}
{% code title="Signature" %}
c.SendStatus(status int)
{% endcode %}
{% code title="Example" %}
app.Get("/not-found", func(c *fiber.Ctx) {
c.SendStatus(415)
// => 415 "Unsupported Media Type"
c.Send("Hello, World!")
c.SendStatus(415)
// => 415 "Hello, World!"
})
{% endcode %}
Sets the response’s HTTP header field to the specified key
, value
.
{% code title="Signature" %}
c.Set(field, value string)
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.Set("Content-Type", "text/plain")
// => "Content-type: text/plain"
})
{% endcode %}
https://expressjs.com/en/4x/api.html#req.fresh
{% hint style="info" %} Not implemented yet, pull requests are welcome! {% endhint %}
Sets the HTTP status for the response.
{% hint style="info" %} Method is a chainable. {% endhint %}
{% code title="Signature" %}
c.Status(status int)
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.Status(fiber.StatusOK)
c.Status(fiber.StatusBadRequest).Send("Bad Request")
c.Status(fiber.StatusNotFound).SendFile("./public/gopher.png")
})
{% endcode %}
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.
{% code title="Signature" %}
c.Subdomains(offset ...int) []string
{% endcode %}
{% code title="Example" %}
// Host: "tobi.ferrets.example.com"
app.Get("/", func(c *fiber.Ctx) {
c.Subdomains() // ["ferrets", "tobi"]
c.Subdomains(1) // ["tobi"]
})
{% endcode %}
Sets the Content-Type HTTP header to the MIME type listed here specified by the file extension.
{% code title="Signature" %}
c.Type(t string) string
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.Type(".html") // => "text/html"
c.Type("html") // => "text/html"
c.Type("json") // => "application/json"
c.Type("png") // => "image/png"
})
{% endcode %}
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.
{% hint style="info" %} Multiple fields are allowed. {% endhint %}
{% code title="Signature" %}
c.Vary(field ...string)
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.Vary("Origin") // => Vary: Origin
c.Vary("User-Agent") // => Vary: Origin, User-Agent
// No duplicates
c.Vary("Origin") // => Vary: Origin, User-Agent
c.Vary("Accept-Encoding", "Accept")
// => Vary: Origin, User-Agent, Accept-Encoding, Accept
})
{% endcode %}
Appends any input to the HTTP body response.
{% code title="Signature" %}
c.Write(body ...interface{})
{% endcode %}
{% code title="Example" %}
app.Get("/", func(c *fiber.Ctx) {
c.Write("Hello, ") // => "Hello, "
c.Write([]byte("World! ")) // => "Hello, World! "
c.Write(123) // => "Hello, World! 123"
})
{% endcode %}
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).
{% code title="Signature" %}
c.XHR() bool
{% endcode %}
{% code title="Example" %}
// X-Requested-With: XMLHttpRequest
app.Get("/", func(c *fiber.Ctx) {
c.XHR() // true
})
{% endcode %}