🧠 Ctx

Accepts(内容协商)

判断请求中是否接受指定的 扩展名内容类型

📌 说明:
依据请求的 Accept HTTP 头判断。

签名

  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

  1. // Accept: text/html, application/json; q=0.8, text/plain; q=0.5; charset="utf-8"
  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("text/plain", "application/json") // "application/json"(根据权重)
  8. c.Accepts("image/png") // ""
  9. c.Accepts("png") // ""
  10. })

示例 2

  1. // Accept: text/html, text/*, application/json, */*; q=0
  2. app.Get("/", func(c *fiber.Ctx) error {
  3. c.Accepts("text/plain", "application/json") // "application/json",更具体
  4. c.Accepts("application/json", "text/html") // "text/html",因为是第一个匹配
  5. c.Accepts("image/png") // "",因为 */* 的 q=0,表示不可接受
  6. })

示例 3:支持 Media-Type 参数

  1. // Accept: text/plain, application/json; version=1; foo=bar
  2. app.Get("/", func(c *fiber.Ctx) error {
  3. c.Accepts("text/plain;format=flowed") // "text/plain;format=flowed"
  4. c.Accepts("application/json") // ""(缺少参数)
  5. c.Accepts(`application/json;foo="bar";VERSION=1`) // 支持参数顺序和大小写,返回匹配值
  6. })

示例 4:权重和优先级

  1. // Accept: text/plain;format=flowed;q=0.9, text/plain
  2. app.Get("/", func(c *fiber.Ctx) error {
  3. c.Accepts("text/plain;format=flowed", "text/plain") // "text/plain;format=flowed"(因为顺序在前)
  4. c.Accepts("text/plain", "text/plain;format=flowed") // "text/plain"
  5. })

AcceptsCharsets / AcceptsEncodings / AcceptsLanguages 示例

  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") // "iso-8859-1"
  6. c.AcceptsEncodings("compress", "br") // "compress"
  7. c.AcceptsLanguages("pt", "nl", "ru") // "nl"
  8. })

AllParams

获取所有路由参数。

签名

  1. func (c *Ctx) AllParams() map[string]string

示例

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

App

返回当前 *App 引用,可以访问应用设置。

示例

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

Append

向响应头添加字段值。

如果该字段尚未设置,将会创建它。

示例

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

Attachment

设置响应为附件(Content-Disposition: attachment

示例

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

BaseURL

返回基础 URL(协议 + 主机名)

示例

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

Bind

为模板引擎绑定默认视图变量。

示例

  1. app.Use(func(c *fiber.Ctx) error {
  2. c.Bind(fiber.Map{
  3. "Title": "Hello, World!",
  4. })
  5. })
  6. app.Get("/", func(c *fiber.Ctx) error {
  7. return c.Render("xxx.tmpl", fiber.Map{}) // 可在模板中使用 Title 变量
  8. })

BodyRaw

返回原始请求体(未解码)

示例

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

⚠️ 该返回值仅在 handler 中有效。请复制数据或使用 Immutable 设置。


Body

根据 Content-Encoding 解压请求体。如果无此 header,则行为同 BodyRaw

示例

  1. // echo 'user=john' | gzip | curl -v -i --data-binary @- -H "Content-Encoding: gzip" http://localhost:8080
  2. app.Post("/", func(c *fiber.Ctx) error {
  3. return c.Send(c.Body()) // 解压后的内容:[]byte("user=john")
  4. })

BodyParser

将请求体绑定到结构体。

📌 根据 Content-Type 设置正确的 struct tag:

Content-Type Struct Tag
application/x-www-form-urlencoded form
multipart/form-data form
application/json json
application/xmltext/xml xml

multipart/form-data 不自动绑定文件,需使用 FormFile 等方法处理文件。

签名

  1. func (c *Ctx) BodyParser(out interface{}) error

示例

  1. type Person struct {
  2. Name string `json:"name" xml:"name" form:"name"`
  3. Pass string `json:"pass" xml:"pass" form:"pass"`
  4. }
  5. app.Post("/", func(c *fiber.Ctx) error {
  6. p := new(Person)
  7. if err := c.BodyParser(p); err != nil {
  8. return err
  9. }
  10. log.Println(p.Name) // john
  11. log.Println(p.Pass) // doe
  12. })

ClearCookie

清除客户端 cookie(如果参数为空,则清除所有)

签名

  1. func (c *Ctx) ClearCookie(key ...string)

示例

  1. app.Get("/", func(c *fiber.Ctx) error {
  2. c.ClearCookie() // 清除所有 cookie
  3. c.ClearCookie("user") // 清除 user cookie
  4. c.ClearCookie("token", "session", "track_id") // 清除多个 cookie
  5. })

⚠️ 浏览器只有在清除时的参数与设置时一致时才会清除 cookie(除 ExpiresMaxAge 外)

示例:手动设置过期时间

  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. app.Get("/delete", func(c *fiber.Ctx) error {
  11. c.Cookie(&fiber.Cookie{
  12. Name: "token",
  13. Expires: time.Now().Add(-(2 * time.Hour)),
  14. HTTPOnly: true,
  15. SameSite: "lax",
  16. })
  17. })

ClientHelloInfo

获取 TLS 握手的客户端信息。
详情参考 Go 官方文档:ClientHelloInfo

示例

  1. app.Get("/hello", func(c *fiber.Ctx) error {
  2. chi := c.ClientHelloInfo()
  3. // 可用于 TLS 配置回调逻辑
  4. })

Context

返回一个兼容 context.Context 接口的 *fasthttp.RequestCtx,该接口要求具有截止时间、取消信号和在 API 边界间传递的其他值。

签名:

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

📘 更多信息请参阅 Fasthttp 官方文档


Cookie

设置 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. SessionOnly bool `json:"session_only"`
  12. }

示例:

  1. app.Get("/", func(c *fiber.Ctx) error {
  2. cookie := new(fiber.Cookie)
  3. cookie.Name = "john"
  4. cookie.Value = "doe"
  5. cookie.Expires = time.Now().Add(24 * time.Hour)
  6. c.Cookie(cookie)
  7. return nil
  8. })

CookieParser

类似于 BodyParser,但用于解析 cookie 参数。需使用 cookie 的结构标签。

签名:

  1. func (c *Ctx) CookieParser(out interface{}) error

示例:

  1. type Person struct {
  2. Name string `cookie:"name"`
  3. Age int `cookie:"age"`
  4. Job bool `cookie:"job"`
  5. }
  6. app.Get("/", func(c *fiber.Ctx) error {
  7. p := new(Person)
  8. if err := c.CookieParser(p); err != nil {
  9. return err
  10. }
  11. log.Println(p.Name) // Joseph
  12. log.Println(p.Age) // 23
  13. log.Println(p.Job) // true
  14. return nil
  15. })
  16. // curl --cookie "name=Joseph; age=23; job=true" http://localhost:8000/

Cookies

通过键名获取 Cookie 值。可以传递默认值。

签名:

  1. func (c *Ctx) Cookies(key string, defaultValue ...string) string

示例:

  1. app.Get("/", func(c *fiber.Ctx) error {
  2. c.Cookies("name") // "john"
  3. c.Cookies("empty", "doe") // "doe"
  4. return nil
  5. })

⚠️ 返回值仅在当前处理器中有效。请勿保存引用,可使用 Immutable 设置来创建副本。


Download

以附件形式发送文件。

签名:

  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. // 或者自定义下载文件名:
  4. return c.Download("./files/report-12345.pdf", "report.pdf")
  5. })

Format

根据 Accept 头进行内容协商。

签名:

  1. func (c *Ctx) Format(body interface{}) error

示例:

  1. app.Get("/", func(c *fiber.Ctx) error {
  2. return c.Format("Hello, World!")
  3. })

如果没有匹配项,则默认为 text/plain


FormFile

通过字段名获取表单中的第一个上传文件。

签名:

  1. func (c *Ctx) FormFile(key string) (*multipart.FileHeader, error)

示例:

  1. app.Post("/", func(c *fiber.Ctx) error {
  2. file, err := c.FormFile("document")
  3. if err != nil {
  4. return err
  5. }
  6. return c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
  7. })

FormValue

通过字段名获取表单值(取第一个值)。

签名:

  1. func (c *Ctx) FormValue(key string, defaultValue ...string) string

示例:

  1. app.Post("/", func(c *fiber.Ctx) error {
  2. name := c.FormValue("name")
  3. return c.SendString(name)
  4. })

⚠️ 返回值仅在当前处理器中有效。请勿保存引用。


Fresh

如果响应在客户端缓存中仍然是 新鲜的,则返回 true,否则返回 false。

当客户端发送 Cache-Control: no-cache 请求头时,Fresh 会返回 false。

签名:

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

📘 参考:Express req.fresh


Get

获取指定 HTTP 请求头。

📌 大小写不敏感。

签名:

  1. func (c *Ctx) Get(key string, defaultValue ...string) string

示例:

  1. app.Get("/", func(c *fiber.Ctx) error {
  2. contentType := c.Get("Content-Type")
  3. return c.SendString(contentType)
  4. })

GetReqHeaders

返回所有请求头,结果为一个 map[string][]string,支持一个键有多个值。

签名:

  1. func (c *Ctx) GetReqHeaders() map[string][]string

⚠️ 返回值仅在当前处理器中有效。


GetRespHeader

获取指定的响应头。

签名:

  1. func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string

示例:

  1. app.Get("/", func(c *fiber.Ctx) error {
  2. id := c.GetRespHeader("X-Request-Id")
  3. return c.SendString(id)
  4. })

GetRespHeaders

获取所有响应头,结果为一个 map[string][]string

签名:

  1. func (c *Ctx) GetRespHeaders() map[string][]string

GetRouteURL

根据命名路由生成路径(相对 URL)。

签名:

  1. func (c *Ctx) GetRouteURL(routeName string, params Map) (string, error)

示例:

  1. app.Get("/", func(c *fiber.Ctx) error {
  2. return c.SendString("首页")
  3. }).Name("home")
  4. app.Get("/user/:id", func(c *fiber.Ctx) error {
  5. return c.SendString(c.Params("id"))
  6. }).Name("user.show")
  7. app.Get("/test", func(c *fiber.Ctx) error {
  8. location, _ := c.GetRouteURL("user.show", fiber.Map{"id": 1})
  9. return c.SendString(location)
  10. })
  11. // 访问 /test 返回 "/user/1"

Hostname

返回从 Host HTTP 头中提取的主机名。

签名

  1. func (c *Ctx) Hostname() string

示例

  1. // GET http://google.com/searchapp.Get("/", func(c *fiber.Ctx) error { c.Hostname() // "google.com" // ...})

返回值仅在处理函数中有效。不要存储任何引用。
请复制或使用[
Immutable](/api/ctx)设置。 了解更多…

IP

返回请求的远程 IP 地址。

签名

  1. func (c *Ctx) IP() string

示例

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

当在 Fiber 应用中注册代理请求头时,返回的 IP 地址是头中的值 (Fiber 配置)

  1. app := fiber.New(fiber.Config{ ProxyHeader: fiber.HeaderXForwardedFor,})

IPs

返回 X-Forwarded-For 请求头中指定的 IP 地址数组。

签名

  1. func (c *Ctx) IPs() []string

示例

  1. // X-Forwarded-For: proxy1, 127.0.0.1, proxy3app.Get("/", func(c *fiber.Ctx) error { c.IPs() // ["proxy1", "127.0.0.1", "proxy3"] // ...})

注意

不当使用 X-Forwarded-For 头可能带来安全风险。详细信息请参见 安全性和隐私问题 部分。

Is

如果传入请求的 Content-Type HTTP 头与指定的 MIME 类型匹配,返回匹配的 内容类型

信息

如果请求没有 主体,则返回 false

签名

  1. func (c *Ctx) Is(extension string) bool

示例

  1. // Content-Type: text/html; charset=utf-8app.Get("/", func(c *fiber.Ctx) error { c.Is("html") // true c.Is(".html") // true c.Is("json") // false // ...})

IsFromLocal

如果请求来自本地主机,则返回 true。

签名

  1. func (c *Ctx) IsFromLocal() bool {

示例

  1. app.Get("/", func(c *fiber.Ctx) error { // 如果请求来自本地主机,返回 true 否则返回 false c.IsFromLocal() // ...})

JSON

使用 encoding/json 包将任何 interfacestring 转换为 JSON。

信息

JSON 还会将内容头设置为 ctype 参数。如果没有传递 ctype,则头会被设置为 application/json

签名

  1. func (c *Ctx) JSON(data interface{}, ctype ...string) error

示例

  1. type SomeStruct struct { Name string Age uint8}app.Get("/json", func(c *fiber.Ctx) error { // 创建数据结构: 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}" return c.JSON(fiber.Map{ "type": "https://example.com/probs/out-of-credit", "title": "You do not have enough credit.", "status": 403, "detail": "Your current balance is 30, but that costs 50.", "instance": "/account/12345/msgs/abc", }, "application/problem+json") // => Content-Type: application/problem+json // => "{ // => "type": "https://example.com/probs/out-of-credit", // => "title": "You do not have enough credit.", // => "status": 403, // => "detail": "Your current balance is 30, but that costs 50.", // => "instance": "/account/12345/msgs/abc", // => }"})

JSONP

发送支持 JSONP 的 JSON 响应。此方法与 JSON 相同,唯一的区别是它支持 JSONP 回调。默认的回调名称为 callback。

可以通过传递 指定名称的字符串 来覆盖此名称。

签名

  1. func (c *Ctx) JSONP(data interface{}, callback ...string) error

示例

  1. type SomeStruct struct { name string age uint8}app.Get("/", func(c *fiber.Ctx) error { // 创建数据结构: 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})})

Links

将链接连接到 Link HTTP 头,以便填充响应的 Link 头字段。

签名

  1. func (c *Ctx) Links(link ...string)

示例

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

一个方法,用于存储作用域仅限于请求的变量,因此只有匹配请求的路由可以访问这些变量。存储的变量在请求处理完后会被移除。如果存储的数据实现了 io.Closer 接口,那么在移除前会调用其 Close 方法。

提示

如果你想将一些 特定的 数据传递到下一个中间件,可以使用它。记得在检索数据时进行类型断言,以确保它是期望的类型。你还可以使用非导出的类型作为键,以避免冲突。

签名

  1. func (c *Ctx) Locals(key interface{}, value ...interface{}) interface{}

示例

  1. type keyType struct{}var userKey keyTypeapp.Use(func(c *fiber.Ctx) error { c.Locals(userKey, "admin") // 使用非导出类型键存储字符串 "admin" return c.Next()})app.Get("/admin", func(c *fiber.Ctx) error { user, ok := c.Locals(userKey).(string) // 获取存储的数据并进行类型断言 if ok && user == "admin" { return c.Status(fiber.StatusOK).SendString("Welcome, admin!") } return c.SendStatus(fiber.StatusForbidden)})

Location

设置响应的 Location HTTP 头为指定的路径参数。

签名

  1. func (c *Ctx) Location(path string)

示例

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

Method

返回请求的 HTTP 方法对应的字符串:GETPOSTPUT 等。
可选地,你可以通过传递一个字符串来覆盖该方法。

签名

  1. func (c *Ctx) Method(override ...string) string

示例

  1. app.Post("/", func(c *fiber.Ctx) error { c.Method() // "POST" c.Method("GET") c.Method() // GET // ...})

MultipartForm

要访问 multipart 表单条目,你可以使用 MultipartForm() 解析二进制数据。返回一个 map[string][]string,所以给定一个键,值将是一个字符串切片。

签名

  1. func (c *Ctx) MultipartForm() (*multipart.Form, error)

示例

  1. app.Post("/", func(c *fiber.Ctx) error { // 解析 multipart 表单: if form, err := c.MultipartForm(); err == nil { // => *multipart.Form if token := form.Value["token"]; len(token) > 0 { // 获取键值: fmt.Println(token[0]) } // 获取 "documents" 键下的所有文件: files := form.File["documents"] // => []*multipart.FileHeader // 遍历文件: for _, file := range files { fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0]) // => "tutorial.pdf" 360641 "application/pdf" // 保存文件到磁盘: if err := c.SaveFile(file, fmt.Sprintf("./%s", file.Filename)); err != nil { return err } } } return err})

Next

Next 被调用时,它会执行匹配当前路由的下一个方法。你可以在方法中传递一个错误结构,这将结束链式调用并调用 错误处理程序

签名

  1. func (c *Ctx) Next() error

示例

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

返回原始请求 URL。

签名

  1. func (c *Ctx) OriginalURL() string

示例

  1. // GET http://example.com/search?q=somethingapp.Get("/", func(c *fiber.Ctx) error { c.OriginalURL() // "/search?q=something" // ...})

返回值仅在处理函数中有效。不要存储任何引用。
请复制或使用[
Immutable](/api/ctx)设置。 了解更多…

Params

该方法可用于获取路由参数,你可以传递一个可选的默认值,如果参数键不存在,则返回默认值。

信息

如果参数 不存在,默认返回空字符串("")。

签名

  1. func (c *Ctx) Params(key string, defaultValue ...string) string

示例

  1. // GET http://example.com/user/fennyapp.Get("/user/:name", func(c *fiber.Ctx) error { c.Params("name") // "fenny" // ...})// GET http://example.com/user/fenny/123app.Get("/user/*", func(c *fiber.Ctx) error { c.Params("*") // "fenny/123" c.Params("*1") // "fenny/123" // ...})

未命名的路由参数(*,+)可以通过 字符计数器 来获取。

示例

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

由于 向后兼容性,也可以直接通过参数字符访问第一个参数段,无需计数器。

示例

  1. app.Get("/v1/*/shop/*", func(c *fiber.Ctx) error { c.Params("*") // 输出第一个通配符段的值})

返回值仅在处理函数中有效。不要存储任何引用。
请复制或使用[
Immutable](/api/ctx)设置。 了解更多…

ParamsInt

该方法可用于获取路由参数中的整数。请注意,如果该参数不在请求中,将返回零。如果该参数不是数字,则将返回零和错误。

信息

如果参数 不存在,默认返回整数零(0)。

签名

  1. func (c *Ctx) ParamsInt(key string) (int, error)

示例

  1. // GET http://example.com/user/123app.Get("/user/:id", func(c *fiber.Ctx) error { id, err := c.ParamsInt("id") // int 123 且没有错误 // ...})

此方法相当于使用 atoi 与 ctx.Params

ParamsParser

这个方法和 BodyParser 类似,但是用于解析路径参数。使用 “params” 这个结构标签非常重要。例如,如果你想解析一个名为 Pass 的路径参数,你需要在结构体字段中使用 params:"pass"

签名

  1. func (c *Ctx) ParamsParser(out interface{}) error

示例

  1. // GET http://example.com/user/111app.Get("/user/:id", func(c *fiber.Ctx) error { param := struct {ID uint `params:"id"`}{} c.ParamsParser(&param) // "{"id": 111}" // ...})

Path

包含请求 URL 的路径部分。你也可以通过传递一个字符串来覆盖路径。对于内部重定向,你可能需要调用 RestartRouting 而不是 Next

签名

  1. func (c *Ctx) Path(override ...string) string

示例

  1. // GET http://example.com/users?sort=descapp.Get("/users", func(c *fiber.Ctx) error { c.Path() // "/users" c.Path("/john") c.Path() // "/john" // ...})

Protocol

包含请求协议字符串:对于 TLS 请求,可能是 httphttps

签名

  1. func (c *Ctx) Protocol() string

示例

  1. // GET http://example.comapp.Get("/", func(c *fiber.Ctx) error { c.Protocol() // "http" // ...})

Queries

Queries 是一个函数,它返回一个包含每个查询字符串参数的对象。

签名

  1. func (c *Ctx) Queries() map[string]string

示例

  1. // GET http://example.com/?name=alex&want_pizza=false&id=app.Get("/", func(c *fiber.Ctx) error { m := c.Queries() m["name"] // "alex" m["want_pizza"] // "false" m["id"] // "" // ...})

示例

  1. // GET http://example.com/?field1=value1&field1=value2&field2=value3app.Get("/", func (c *fiber.Ctx) error { m := c.Queries() m["field1"] // "value2" m["field2"] // value3})

示例

  1. // GET http://example.com/?list_a=1&list_a=2&list_a=3&list_b[]=1&list_b[]=2&list_b[]=3&list_c=1,2,3app.Get("/", func(c *fiber.Ctx) error { m := c.Queries() m["list_a"] // "3" m["list_b[]"] // "3" m["list_c"] // "1,2,3"})

示例

  1. // GET /api/posts?filters.author.name=John&filters.category.name=Technologyapp.Get("/", func(c *fiber.Ctx) error { m := c.Queries() m["filters.author.name"] // John m["filters.category.name"] // Technology})

示例

  1. // GET /api/posts?tags=apple,orange,banana&filters[tags]=apple,orange,banana&filters[category][name]=fruits&filters.tags=apple,orange,banana&filters.category.name=fruitsapp.Get("/", func(c *fiber.Ctx) error { m := c.Queries() m["tags"] // apple,orange,banana m["filters[tags]"] // apple,orange,banana m["filters[category][name]"] // fruits m["filters.tags"] // apple,orange,banana m["filters.category.name"] // fruits})

Query

这个属性是一个对象,包含每个查询字符串参数的属性,你可以传递一个可选的默认值,如果查询键不存在,它将返回该默认值。

信息

如果没有查询字符串,它会返回一个空字符串。

签名

  1. func (c *Ctx) Query(key string, defaultValue ...string) string

示例

  1. // GET http://example.com/?order=desc&brand=nikeapp.Get("/", func(c *fiber.Ctx) error { c.Query("order") // "desc" c.Query("brand") // "nike" c.Query("empty", "nike") // "nike" // ...})

返回的值只在处理程序内有效。不要存储任何引用。
使用
Immutable 设置来代替。 了解更多…

QueryBool

这个属性是一个对象,包含每个查询布尔参数的属性,你可以传递一个可选的默认值,如果查询键不存在,它将返回该默认值。

注意

请注意,如果该参数不在请求中,默认返回 false。如果该参数不是布尔值,它仍然会尝试转换,并通常返回 false。

签名

  1. func (c *Ctx) QueryBool(key string, defaultValue ...bool) bool

示例

  1. // GET http://example.com/?name=alex&want_pizza=false&id=app.Get("/", func(c *fiber.Ctx) error { c.QueryBool("want_pizza") // false c.QueryBool("want_pizza", true) // false c.QueryBool("name") // false c.QueryBool("name", true) // true c.QueryBool("id") // false c.QueryBool("id", true) // true // ...})

QueryFloat

这个属性是一个对象,包含每个查询 float64 参数的属性,你可以传递一个可选的默认值,如果查询键不存在,它将返回该默认值。

注意

请注意,如果该参数不在请求中,默认返回零。如果该参数不是数字,它仍然会尝试转换,并通常返回 1。

信息

如果参数不存在,默认为 float64 的零值(0)。

签名

  1. func (c *Ctx) QueryFloat(key string, defaultValue ...float64) float64

示例

  1. // GET http://example.com/?name=alex&amount=32.23&id=app.Get("/", func(c *fiber.Ctx) error { c.QueryFloat("amount") // 32.23 c.QueryFloat("amount", 3) // 32.23 c.QueryFloat("name", 1) // 1 c.QueryFloat("name") // 0 c.QueryFloat("id", 3) // 3 // ...})

QueryInt

这个属性是一个对象,包含每个查询整数参数的属性,你可以传递一个可选的默认值,如果查询键不存在,它将返回该默认值。

注意

请注意,如果该参数不在请求中,默认返回零。如果该参数不是数字,它仍然会尝试转换,并通常返回 1。

信息

如果参数不存在,默认为整数的零值(0)。

签名

  1. func (c *Ctx) QueryInt(key string, defaultValue ...int) int

示例

  1. // GET http://example.com/?name=alex&wanna_cake=2&id=app.Get("/", func(c *fiber.Ctx) error { c.QueryInt("wanna_cake", 1) // 2 c.QueryInt("name", 1) // 1 c.QueryInt("id", 1) // 1 c.QueryInt("id") // 0 // ...})

QueryParser

这个方法和 BodyParser 类似,但是用于解析查询参数。使用 “query” 这个结构标签非常重要。例如,如果你想解析一个查询参数,字段名叫 Pass,你应该在结构体字段中使用 query:"pass"

签名

  1. func (c *Ctx) QueryParser(out interface{}) error

示例

  1. // 字段名应该以大写字母开头type Person struct { Name string `query:"name"` Pass string `query:"pass"` Products []string `query:"products"`}app.Get("/", func(c *fiber.Ctx) error { p := new(Person) if err := c.QueryParser(p); err != nil { return err } log.Println(p.Name) // john log.Println(p.Pass) // doe // fiber.Config{EnableSplittingOnParsers: false} - 默认 log.Println(p.Products) // ["shoe,hat"] // fiber.Config{EnableSplittingOnParsers: true} // log.Println(p.Products) // ["shoe", "hat"] // ...})// 使用以下 curl 命令运行测试// curl "http://localhost:3000/?name=john&pass=doe&products=shoe,hat"

信息

有关更多解析器设置,请查看 Config

Range

将返回一个包含类型和范围切片的结构体。

签名

  1. func (c *Ctx) Range(size int) (Range, error)

示例

  1. // Range: bytes=500-700, 700-900app.Get("/", func(c *fiber.Ctx) error { b := c.Range(1000) if b.Type == "bytes" { for r := range r.Ranges { fmt.Println(r) // [500, 700] } }})

Redirect

重定向到由指定路径派生的 URL,指定的状态码是一个正整数,表示 HTTP 状态码。

信息

如果没有指定,状态默认是 302 Found

签名

  1. func (c *Ctx) Redirect(location string, status ...int) error

示例

  1. app.Get("/coffee", func(c *fiber.Ctx) error { return c.Redirect("/teapot")})app.Get("/teapot", func(c *fiber.Ctx) error { return c.Status(fiber.StatusTeapot).Send("🍵 short and stout 🍵")})

更多示例

  1. app.Get("/", func(c *fiber.Ctx) error { return c.Redirect("/foo/bar") return c.Redirect("../login") return c.Redirect("http://example.com") return c.Redirect("http://example.com", 301)})

RedirectToRoute

重定向到特定路由,并携带参数以及指定的状态码,状态码是一个正整数,表示 HTTP 状态码。

信息

如果没有指定,状态默认是 302 Found

信息

如果你想将查询传递给路由,你必须在参数中添加 “queries” 键,类型为 map[string]string

签名

  1. func (c *Ctx) RedirectToRoute(routeName string, params fiber.Map, status ...int) error

示例

  1. app.Get("/", func(c *fiber.Ctx) error { // /user/fiber return c.RedirectToRoute("user", fiber.Map{ "name": "fiber" })})app.Get("/with-queries", func(c *fiber.Ctx) error { // /user/fiber?data[0][name]=john&data[0][age]=10&test=doe return c.RedirectToRoute("user", fiber.Map{ "name": "fiber", "queries": map[string]string{"data[0][name]": "john", "data[0][age]": "10", "test": "doe"}, })})app.Get("/user/:name", func(c *fiber.Ctx) error { return c.SendString(c.Params("name"))}).Name("user")

RedirectBack

将请求重定向回来源 URL。如果 refer header 不存在,则会重定向到指定的 fallback URL,并使用指定的状态码,状态码是一个正整数,对应 HTTP 状态码。

info

如果 未指定,状态码默认为 302 Found

函数签名

  1. func (c *Ctx) RedirectBack(fallback string, status ...int) error

示例

  1. app.Get("/", func(c *fiber.Ctx) error { return c.SendString("Home page")})
  2. app.Get("/test", func(c *fiber.Ctx) error { c.Set("Content-Type", "text/html") return c.SendString(`<a href="/back">Back</a>`)})
  3. app.Get("/back", func(c *fiber.Ctx) error { return c.RedirectBack("/")})

Render

渲染一个视图并返回 text/html 响应。默认情况下,Render 使用默认的 Go 模板引擎。如果你想使用其他视图引擎,请查看我们的 模板中间件

函数签名

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

Request

返回 *fasthttp.Request 指针。

函数签名

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

示例

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

ReqHeaderParser

这个方法类似于 BodyParser,但是用于解析请求头。使用结构体标签 “reqHeader” 非常重要。例如,如果你想解析一个名为 Pass 的请求头,你应该使用结构体字段 reqHeader:"pass"

函数签名

  1. func (c *Ctx) ReqHeaderParser(out interface{}) error

示例

  1. // 字段名称应以大写字母开头
  2. type Person struct {
  3. Name string `reqHeader:"name"`
  4. Pass string `reqHeader:"pass"`
  5. Products []string `reqHeader:"products"`
  6. }
  7. app.Get("/", func(c *fiber.Ctx) error {
  8. p := new(Person)
  9. if err := c.ReqHeaderParser(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. // 通过以下 curl 命令运行测试
  18. // curl "http://localhost:3000/" -H "name: john" -H "pass: doe" -H "products: shoe,hat"

Response

返回 *fasthttp.Response 指针。

函数签名

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

示例

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

RestartRouting

当调用 Next 时,RestartRouting 会从当前路由匹配的第一个方法开始重新执行。这在重写路径后可能会很有用,例如内部分发。注意,处理程序可能会再次执行,这可能会导致无限循环。

函数签名

  1. func (c *Ctx) RestartRouting() error

示例

  1. app.Get("/new", func(c *fiber.Ctx) error { return c.SendString("From /new")})
  2. app.Get("/old", func(c *fiber.Ctx) error { c.Path("/new") return c.RestartRouting()})

Route

返回匹配的 Route 结构。

函数签名

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

注意

不要在中间件中依赖 c.Route() 调用 c.Next() 之前 - c.Route() 返回 最后执行的路由

示例

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

SaveFile

用于将 任何 多部分文件保存到磁盘。

函数签名

  1. func (c *Ctx) SaveFile(fh *multipart.FileHeader, path string) error

示例

  1. app.Post("/", func(c *fiber.Ctx) error {
  2. // 解析多部分表单:
  3. if form, err := c.MultipartForm(); err == nil {
  4. // => *multipart.Form
  5. // 获取所有文件:
  6. files := form.File["documents"]
  7. // => []*multipart.FileHeader
  8. // 遍历文件:
  9. for _, file := range files {
  10. fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0])
  11. // => "tutorial.pdf" 360641 "application/pdf"
  12. // 保存文件到磁盘:
  13. if err := c.SaveFile(file, fmt.Sprintf("./%s", file.Filename)); err != nil {
  14. return err
  15. }
  16. }
  17. return err
  18. }})

SaveFileToStorage

用于将 任何 多部分文件保存到外部存储系统。

函数签名

  1. func (c *Ctx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error

示例

  1. storage := memory.New()
  2. app.Post("/", func(c *fiber.Ctx) error {
  3. // 解析多部分表单:
  4. if form, err := c.MultipartForm(); err == nil {
  5. // => *multipart.Form
  6. // 获取所有文件:
  7. files := form.File["documents"]
  8. // => []*multipart.FileHeader
  9. // 遍历文件:
  10. for _, file := range files {
  11. fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0])
  12. // => "tutorial.pdf" 360641 "application/pdf"
  13. // 保存文件到存储:
  14. if err := c.SaveFileToStorage(file, fmt.Sprintf("./%s", file.Filename), storage); err != nil {
  15. return err
  16. }
  17. }
  18. return err
  19. }})

Secure

一个布尔值属性,如果建立了 TLS 连接,则为 true

函数签名

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

示例

  1. // Secure() 方法等同于:c.Protocol() == "https"

Send

设置 HTTP 响应体。

函数签名

  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 还提供 SendStringSendStream 方法来处理原始输入。

提示

如果你 不需要 类型断言,推荐使用此方法以获得 更快 的性能。

函数签名

  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!") // => "Hello, World!"
  3. return c.SendStream(bytes.NewReader([]byte("Hello, World!"))) // => "Hello, World!"
  4. })

SendFile

从给定路径传输文件。根据文件名的扩展名设置 Content-Type 响应 HTTP 头字段。

注意

该方法默认不使用 gzipping,如果需要启用,请设置为 true

签名

  1. func (c *Ctx) SendFile(file string, compress ...bool) error

示例

  1. app.Get("/not-found", func(c *fiber.Ctx) error { return c.SendFile("./public/404.html"); // 禁用压缩 return c.SendFile("./static/index.html", false);})

信息

如果文件包含特定的 URL 字符,你必须在传递文件路径到 sendFile 函数之前进行转义。

示例

  1. app.Get("/file-with-url-chars", func(c *fiber.Ctx) error { return c.SendFile(url.PathEscape("hash_sign_#.txt"))})

信息

对于从嵌入式文件系统发送文件,可以使用 这个功能

SendStatus

如果响应体 为空,则设置状态码和正确的状态消息。

提示

你可以在 这里 查找所有使用的状态码和消息。

签名

  1. func (c *Ctx) SendStatus(status int) error

示例

  1. app.Get("/not-found", func(c *fiber.Ctx) error { return c.SendStatus(415) // => 415 "Unsupported Media Type" c.SendString("Hello, World!") return c.SendStatus(415) // => 415 "Hello, World!"})

Set

设置响应的 HTTP 头字段为指定的 keyvalue

签名

  1. func (c *Ctx) Set(key string, val string)

示例

  1. app.Get("/", func(c *fiber.Ctx) error { c.Set("Content-Type", "text/plain") // => "Content-type: text/plain" // ...})

SetParserDecoder

允许你根据 schema 的选项配置 BodyParser/QueryParser 解码器,提供可能添加自定义类型用于解析的功能。

签名

  1. func SetParserDecoder(parserConfig fiber.ParserConfig{ IgnoreUnknownKeys bool, ParserType []fiber.ParserType{ Customtype interface{}, Converter func(string) reflect.Value, }, ZeroEmpty bool, SetAliasTag string,})

示例

  1. type CustomTime time.Time// String() 返回字符串形式的时间func (ct *CustomTime) String() string { t := time.Time(*ct).String() return t}// 注册 CustomTime 类型转换器,格式为 2006-01-02var timeConverter = func(value string) reflect.Value { fmt.Println("timeConverter", value) if v, err := time.Parse("2006-01-02", value); err == nil { return reflect.ValueOf(v) } return reflect.Value{}}customTime := fiber.ParserType{ Customtype: CustomTime{}, Converter: timeConverter,}// 将设置添加到解码器fiber.SetParserDecoder(fiber.ParserConfig{ IgnoreUnknownKeys: true, ParserType: []fiber.ParserType{customTime}, ZeroEmpty: true,})// 使用 CustomType 示例,假设自定义时间格式不是 RFC3339类型 Demo struct { Date CustomTime `form:"date" query:"date"` Title string `form:"title" query:"title"` Body string `form:"body" query:"body"`}app.Post("/body", func(c *fiber.Ctx) error { var d Demo c.BodyParser(&d) fmt.Println("d.Date", d.Date.String()) return c.JSON(d)})app.Get("/query", func(c *fiber.Ctx) error { var d Demo c.QueryParser(&d) fmt.Println("d.Date", d.Date.String()) return c.JSON(d)})// curl -X POST -F title=title -F body=body -F date=2021-10-20 http://localhost:3000/body// curl -X GET "http://localhost:3000/query?title=title&body=body&date=2021-10-20"

SetUserContext

设置用户指定的上下文接口实现。

签名

  1. func (c *Ctx) SetUserContext(ctx context.Context)

示例

  1. app.Get("/", func(c *fiber.Ctx) error { ctx := context.Background() c.SetUserContext(ctx) // 这里的 ctx 可以是任何上下文实现 // ...})

Stale

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

签名

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

Status

设置响应的 HTTP 状态。

信息

该方法是 可链式 的。

签名

  1. func (c *Ctx) Status(status int) *Ctx

示例

  1. app.Get("/fiber", func(c *fiber.Ctx) error { c.Status(fiber.StatusOK) return nil}app.Get("/hello", func(c *fiber.Ctx) error { return c.Status(fiber.StatusBadRequest).SendString("Bad Request")}app.Get("/world", func(c *fiber.Ctx) error { return c.Status(fiber.StatusNotFound).SendFile("./public/gopher.png")})

Subdomains

返回请求中域名的子域名字符串切片。

应用程序的子域偏移量属性,默认值为 2,用于确定子域段的起始位置。

签名

  1. func (c *Ctx) Subdomains(offset ...int) []string

示例

  1. // Host: "tobi.ferrets.example.com"app.Get("/", func(c *fiber.Ctx) error { c.Subdomains() // ["ferrets", "tobi"] c.Subdomains(1) // ["tobi"] // ...})

Type

根据文件 扩展名 设置 Content-Type HTTP 头为指定的 MIME 类型,这里 列出了 MIME 类型。

签名

  1. func (c *Ctx) Type(ext string, charset ...string) *Ctx

示例

  1. app.Get("/", func(c *fiber.Ctx) error { c.Type(".html") // => "text/html" c.Type("html") // => "text/html" c.Type("png") // => "image/png" c.Type("json", "utf-8") // => "application/json; charset=utf-8" // ...})

UserContext

UserContext 返回用户之前设置的上下文实现,如果没有设置,则返回一个非空的空上下文。

签名

  1. func (c *Ctx) UserContext() context.Context

示例

  1. app.Get("/", func(c *fiber.Ctx) error { ctx := c.UserContext() // ctx 是用户设置的上下文实现 // ...})

Vary

将给定的头字段添加到 Vary 响应头。如果该字段尚未列出,则会将其附加;否则,它将保留在当前位置。

信息

允许多个字段。

签名

  1. func (c *Ctx) Vary(fields ...string)

示例

  1. app.Get("/", func(c *fiber.Ctx) error { c.Vary("Origin") // => Vary: Origin c.Vary("User-Agent") // => Vary: Origin, User-Agent // 不重复 c.Vary("Origin") // => Vary: Origin, User-Agent c.Vary("Accept-Encoding", "Accept") // => Vary: Origin, User-Agent, Accept-Encoding, Accept // ...})

Write

实现 Writer 接口。

签名

  1. func (c *Ctx) Write(p []byte) (n int, err error)

示例

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

Writef

实现带有变量的字符串。

签名

  1. func (c *Ctx) Writef(f string, a ...interface{}) (n int, err error)

示例

  1. app.Get("/", func(c *fiber.Ctx) error { world := "World!" c.Writef("Hello, %s", world) // => "Hello, World!" fmt.Fprintf(c, "%s\n", "Hello, World!") // "Hello, World!Hello, World!"})

WriteString

实现字符串。

签名

  1. func (c *Ctx) WriteString(s string) (n int, err error)

示例

  1. app.Get("/", func(c *fiber.Ctx) error { c.WriteString("Hello, World!") // => "Hello, World!" fmt.Fprintf(c, "%s\n", "Hello, World!") // "Hello, World!Hello, World!"})

XHR

如果请求的 X-Requested-With 头字段是 XMLHttpRequest,则为 true,表示请求是由客户端库(如 jQuery)发出的。

签名

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

示例

  1. // X-Requested-With: XMLHttpRequestapp.Get("/", func(c *fiber.Ctx) error { c.XHR() // true // ...})

XML

使用标准的 encoding/xml 包将任何 接口字符串 转换为 XML。

信息

XML 还会将内容头设置为 application/xml

签名

  1. func (c *Ctx) XML(data interface{}) error

示例

  1. type SomeStruct struct { XMLName xml.Name `xml:"Fiber"` Name string `xml:"Name"` Age uint8 `xml:"Age"`}app.Get("/", func(c *fiber.Ctx) error { // 创建数据结构: data := SomeStruct{ Name: "Grame", Age: 20, } return c.XML(data) // <Fiber> // <Name>Grame</Name> // <Age>20</Age> // </Fiber>})