# Context The ctx object represents the HTTP request and response and has methods for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the context is always referred to as c but its actual name is determined by the parameters to the callback function in which you’re working. #### Accepts Checks if the specified content types are acceptable, based on the request’s Accept HTTP header field. You can use an extention or content-type format ```go // Function signature c.Accepts(types ...string) string // Example app.Get("/", func(c *fiber.Ctx) { // Accept: text/html c.Accepts("html") // => "html" // Accept: text/*, application/json c.Accepts("html") // => "html" c.Accepts("text/html") //=> "text/html" c.Accepts("json", "text") // => "json" c.Accepts("application/json") // => "application/json" // Accept: text/*, application/json c.Accepts("image/png") c.Accepts("png") // => "" }) ``` #### AcceptsCharsets Returns the first accepted charset of the specified character sets, based on the request’s Accept-Charset HTTP header field ```go // Function signature c.AcceptsCharsets(charsets ...string) string // Example app.Get("/", func(c *fiber.Ctx) { // Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5 c.AcceptsCharsets("utf-8") // => "utf-8" c.AcceptsCharsets("utf-16", "iso-8859-1") // => "iso-8859-1" c.AcceptsCharsets("utf-16") // => "" }) ``` #### AcceptsEncodings Returns the first accepted encoding of the specified encodings, based on the request’s Accept-Encoding HTTP header field. ```go // Function signature c.AcceptsEncodings(encodings ...string) string // Example app.Get("/", func(c *fiber.Ctx) { // Accept-Encoding: gzip, compress;q=0.2 c.AcceptsEncodings("gzip") // => "gzip" c.AcceptsEncodings("compress", "br") // => "compress" c.AcceptsEncodings("deflate") // => "" }) ``` #### AcceptsLanguages Returns the first accepted language of the specified languages, based on the request’s Accept-Language HTTP header field. ```go // Function signature c.AcceptsLanguages(languages ...string) string // Example app.Get("/", func(c *fiber.Ctx) { // Accept-Language: en;q=0.8, es, pt c.AcceptsLanguages("en") // => "en" c.AcceptsLanguages("pt", "nl") // => "pt" c.AcceptsLanguages("fr") // => "" }) ``` #### 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. The value parameter must be a string. ```go // Function signature c.Append(field, values ...string) // Example app.Get("/", func(c *fiber.Ctx) { // Let's see if the Link header exist c.Get("Link") // => "" 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](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header field to “attachment”. If a filename is given, then it sets the Content-Type based on the extension name via [Type](#type), and sets the Content-Disposition “filename=” parameter. ```go // Function signature c.Attachment(file ...string) // Example app.Get("/", func(c *fiber.Ctx) { c.Attachment() // => Content-Disposition: attachment c.Attachment("./static/img/logo.png") // => Content-Disposition: attachment; filename="logo.png" // => Content-Type: image/png }) ``` #### BaseURL #### AcceptsLanguages Returns the base URL, protocol and hostname combined. ```go // Function signature c.BaseURL() bool // Example app.Get("/", func(c *fiber.Ctx) { // http://webtech.oregonstate.edu/faq/page/2?sort=date c.BaseURL() // => "http://webtech.oregonstate.edu" }) ``` #### BasicAuth BasicAuth returns the username and password provided in the request's Authorization header, if the request uses [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication). ```go // Function signature c.BasicAuth() (user, pass string, ok bool) // Example // curl --user john:doe http://localhost:8080 app.Get("/", func(c *fiber.Ctx) { user, pass, ok := c.BasicAuth() if !ok || user != "john" || pass != "doe" { c.Status(403).Send("Forbidden") return } c.Send("Welcome " + user) }) ``` #### Body Contains the raw post body submitted in the request. Calling a key in body returns a string value if exist or you loop trough the body params using a key value function callback. The following example shows how to use the body function. ```go // Function signature c.Body() string c.Body(key string) string c.Body(func(key value string)) func(string, string) // Example // curl -X POST http://localhost:8080 -d user=john app.Post("/", func(c *fiber.Ctx) { // Get the raw body post c.Body() // => user=john // Get the body value using specific key c.Body("user") // => "john" // Loop trough all body params c.Body(func(key string, val string) { fmt.Printl(key, val) // => "user" "john" }) }) ``` #### ClearCookie Clears all client cookies or a specific cookie by name by setting the expire date in the past. ```go // Function signature c.ClearCookie() c.ClearCookie(key string) // Example app.Get("/", func(c *fiber.Ctx) { // Clears all cookies c.ClearCookie() // Expire specific cookie c.ClearCookie("user") // Expire multiple cookies c.ClearCookie("token", "session", "track_id", "version") }) ``` #### Cookie Sets cookie name to value, the third options parameter is not implemented yet. ```go // Function signature c.Cookie(name, value string) c.Cookie(name, value string, options *Cookie{}) // Cookie options struct &fiber.Cookie{ Expire int64 // Unix timestamp MaxAge int // Seconds Domain string Path string HttpOnly bool Secure bool SameSite string // "lax", "strict", "none", "" } // Example app.Get("/", func(c *fiber.Ctx) { // Set cookie c.Cookie("name", "john") // => Cookie: name=john; // Set cookie with optionss options := &fiber.Cookie{ Expire: 1579033664, // Use MaxAge instead of Expire, its 2019 // Expire will not be used if MaxAge is set MaxAge: 60, Domain: "example.com", Path: "/", HttpOnly: true, Secure: true, SameSite: "lax", } c.Cookie("name", "john", options) // => name=john; max-age=60; domain=example.com; path=/; HttpOnly; secure; SameSite=Lax }) ``` #### Cookies Get cookies ```go // Function signature c.Cookies() string c.Cookies(key string) string c.Cookies(key []byte) string c.Cookies(func(key, value string)) string // Example app.Get("/", func(c *fiber.Ctx) { // Get raw cookie header c.Cookies() // => name=john; // Get cookie by key c.Cookies("name") c.Cookies([]byte("name")) // => "john" // Show all cookies c.Cookies(func(key, val string) { fmt.Println(key, val) // => "name", "john" }) }) ``` #### Download Transfers the file at path as an “attachment”. Typically, browsers will prompt the user for download. By default, the Content-Disposition header “filename=” parameter is path (this typically appears in the browser dialog). Override this default with the filename parameter. ```go // Function signature c.Download(path string) c.Download(path, filename string) // 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 }) ``` #### !End !> Planned for v2.0.0 #### Fasthttp You can still access and use all Fasthttp methods and properties. Please read the [Fasthttp Documentation](https://godoc.org/github.com/valyala/fasthttp) for more information ```go // Function signature c.Fasthttp... // Example app.Get("/", func(c *fiber.Ctx) { c.Fasthttp.Request.Header.Method() // => []byte("GET") c.Fasthttp.Response.Write([]byte("Hello, World!")) // => "Hello, World!" }) ``` #### Format Performs content-negotiation on the Accept HTTP header. It uses [Accepts](#accepts) to select a proper format. If the header is not specified or there is no proper format, text/plain is used. ```go // Function signature c.Format(body string) c.Format(body []byte) // Example app.Get("/", func(c *fiber.Ctx) { // Accept: text/plain c.Format("Hello, World!") // => Hello, World! // Accept: text/html c.Format("Hello, World!") // =>
Hello, World!
"Hello, World!" }) ``` #### FormFile MultipartForm files can be retrieved by name, the first file from the given key is returned. ```go // Function signature c.FormFile(name string) (*multipart.FileHeader, error) // 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)) } }) ``` #### FormValue MultipartForm values can be retrieved by name, the first value from the given key is returned. ```go // Function signature c.FormValue(name string) string // Example app.Post("/", func(c *fiber.Ctx) { // Get first value from form field "name" c.FormValue("name") // => "john" or "" if not exist }) ``` #### !Fresh !> Planned for v2.0.0 #### Get Returns the HTTP response header specified by field. The match is case-insensitive. ```go // Function signature c.Get(field string) string // Example app.Get("/", func(c *fiber.Ctx) { c.Get("Content-Type") // => "text/plain" c.Get("content-type") // => "text/plain" c.Get("something") // => "" }) ``` #### !HeadersSent !> Planned for v2.0.0 #### Hostname Contains the hostname derived from the Host HTTP header. ```go // Function signature c.Hostname() string // Example app.Get("/", func(c *fiber.Ctx) { // Host: "localhost:8080" c.Hostname() // => "localhost" }) ``` #### Ip Contains the remote IP address of the request. ```go // Function signature c.Ip() string // Example app.Get("/", func(c *fiber.Ctx) { c.Ip() // => "127.0.0.1" }) ``` #### Ips contains an array of IP addresses specified in the X-Forwarded-For request header. ```go // Function signature c.Ips() []string // Example // X-Forwarded-For: proxy1, 127.0.0.1", proxy3 app.Get("/", func(c *fiber.Ctx) { 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, returns false. ```go // Function signature c.Is(typ string) bool // Example app.Get("/", func(c *fiber.Ctx) { // Content-Type: text/html; charset=utf-8 c.Is("html") // => true c.Is(".html") // => true c.Is("json") // => false }) ``` #### JSON Converts any interface or string to json using [Jsoniter](https://github.com/json-iterator/go), this function also sets the content header to application/json. ```go // Function signature c.JSON(v interface{}) error // Example type SomeStruct struct { Name string Age uint8 } app := fiber.New() app.Get("/json", func(c *fiber.Ctx) { data := SomeStruct{ Name: "Grame", Age: 20, } c.JSON(data) // => "{"Name": "Grame", "Age": 20}" c.JSON("Hello, World!") // => "Hello, World!" }) app.Listen(8080) ``` Or with error checking ```go app.Get("/json", func(c *fiber.Ctx) { data := SomeStruct{ Name: "Grame", Age: 20, } if err := c.JSON(data); err != nil { c.Status(500).Send("Bad Request") } // => "{"Name": "Grame", "Age": 20}" }) ``` #### JSONBytes This function accepts raw []byte bodies and sets the content header to application/json. This function is used if you do not need type assertion. ```go // Function signature c.JSON(json []byte) // Example app := fiber.New() app.Get("/json", func(c *fiber.Ctx) { c.JSONBytes([]byte(`"{"hello": "world"}"`)) }) app.Listen(8080) ``` #### JSONP Sends a JSON response with JSONP support. This method is identical to [JSON()](#json), except that it opts-in to JSONP callback support. By default, the JSONP callback name is simply callback. Override this by passing a named string in the function. ```go // Function signature c.JSONP(v interface{}) error c.JSONP(v interface{}, callback string) error // Example type SomeStruct struct { name string age uint8 } app := fiber.New() app.Get("/", func(c *fiber.Ctx) { data := SomeStruct{ name: "Grame", age: 20, } c.JSONP(data) // => callback({"name": "Grame", "age": 20}) c.JSONP(data, "customFunc") // => customFunc({"name": "Grame", "age": 20}) }) app.Listen(8080) ``` #### JSONString This function accepts raw string body and sets the content header to application/json. This function is used if you do not need type assertion. ```go // Function signature c.JSON(json string) // Example app := fiber.New() app.Get("/json", func(c *fiber.Ctx) { c.JSONString(`"{"hello": "world"}"`) }) app.Listen(8080) ``` #### Links Joins the links followed by the propery to populate the response’s Link HTTP header field. ```go // Function signature c.Links(link ...string) // 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: