fiber

package module
v1.36.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 31, 2021 License: MIT Imports: 36 Imported by: 0

README

Fiber

Fiber是一个受到Express启发的Web框架,建立在Go语言写的最快的FasthttpHTTP引擎的基础上。旨在简化 零内存分配提高性能,以便快速开发。

⚡️ 快速入门

package main

import "gitee.com/azhai/fiber-u8l"

func main() {
	app := fiber.New()

	app.Get("/", func(c *fiber.Ctx) error {
		return c.SendString("Hello, World 👋!")
	})

	app.Listen(":3000")
}

🤖 性能

这些测试由TechEmpowerGo Web 执行。如果要查看所有结果,请访问我们的Wiki

⚙️ 安装

首先, 下载并安装Go。 需要1.14或更高版本。

使用go get命令完成安装:

export GO111MODULE=on
export GOPROXY=https://goproxy.cn

go get gitee.com/azhai/fiber-u8l

🎯 特点

💡 哲学

Node.js切换到Go的新gopher在开始构建Web应用程序或微服务之前正在应对学习曲线。 Fiber作为一个Web框架 ,是按照极简主义的思想并遵循UNIX方式创建的,因此新的gopher可以在热烈和可信赖的欢迎中迅速进入Go的世界。

Fiber受到了互联网上最流行的Web框架Express启发 。我们结合了Express易用性Go原始性能 。如果您曾经在Node.js上实现过Web应用程序(使用Express或类似工具),那么许多方法和原理对您来说应该非常易懂

我们关注 整个互联网 用户在issues和Discord channel的消息,为了创建一个迅速灵活以及友好Go web框架,满足任何任务,最后期限和开发者技能。就像ExpressJavaScript世界中一样。

👀 示例

下面列出了一些常见示例。如果您想查看更多代码示例,请访问我们的Recipes代码库或API文档

📖 基础路由
func main() {
	app := fiber.New()

	// GET /john
	app.Get("/:name", func(c *fiber.Ctx) error {
		tpl := "Hello, %s 👋!"
		return c.Printf(tpl, c.ParamStr("name")) // => Hello john 👋!
	})

	// GET /john/75
	app.Get("/:name/:age/:gender?", func(c *fiber.Ctx) error {
		tpl := "👴 %s is %d years old"
		return c.Printf(tpl, c.ParamStr("name"), c.ParamInt("age")) // => 👴 john is 75 years old
	})

	// GET /dictionary.txt
	app.Get("/:file.:ext", func(c *fiber.Ctx) error {
		tpl := "📃 %s.%s"
		return c.Printf(tpl, c.ParamStr("file"), c.ParamStr("ext")) // => 📃 dictionary.txt
	})

	// GET /flights/LAX-SFO
	app.Get("/flights/:from-:to", func(c *fiber.Ctx) error {
		tpl := "💸 From: %s, To: %s"
		return c.Printf(tpl, c.ParamStr("from"), c.ParamStr("to")) // => 💸 From: LAX, To: SFO
	})

	// GET /api/register
	app.Get("/api/*", func(c *fiber.Ctx) error {
		tpl := "✋ %s"
		return c.Printf(tpl, c.ParamStr("*")) // => ✋ /api/register
	})

	log.Fatal(app.Listen(":3000"))
}

📖 静态文件服务
func main() {
	app := fiber.New()

	app.Static("/", "./public")
	// => http://localhost:3000/js/script.js
	// => http://localhost:3000/css/style.css

	app.Static("/prefix", "./public")
	// => http://localhost:3000/prefix/js/script.js
	// => http://localhost:3000/prefix/css/style.css

	app.Static("*", "./public/index.html")
	// => http://localhost:3000/any/path/shows/index/html

	log.Fatal(app.Listen(":3000"))
}

📖 中间件Next
func main() {
	app := fiber.New()

	// Match any route
	app.Use(func(c *fiber.Ctx) error {
		fmt.Println("🥇 First handler")
		return c.Next()
	})

	// Match all routes starting with /api
	app.Use("/api", func(c *fiber.Ctx) error {
		fmt.Println("🥈 Second handler")
		return c.Next()
	})

	// GET /api/register
	app.Get("/api/list", func(c *fiber.Ctx) error {
		fmt.Println("🥉 Last handler")
		return c.SendString("Hello, World 👋!")
	})

	log.Fatal(app.Listen(":3000"))
}

📚 展示更多代码示例

模版引擎

📖 配置 📖 模版引擎 📖 渲染

如果未设置模版引擎,则Fiber默认使用html/template

如果您要执行部分模版或使用其他引擎,例如amberhandlebarsmustache或者pug等等...

请查看我们的Template包,该包支持多个模版引擎。

package main

import (
	"gitee.com/azhai/fiber-u8l"
	"github.com/gofiber/template/pug"
)

func main() {
	// You can setup Views engine before initiation app:
	app := fiber.New(fiber.Config{
		Views: pug.New("./views", ".pug"),
	})

	// And now, you can call template `./views/home.pug` like this:
	app.Get("/", func(c *fiber.Ctx) error {
		return c.Render("home", fiber.Map{
			"title": "Homepage",
			"year":  1999,
		})
	})

	log.Fatal(app.Listen(":3000"))
}

组合路由链

📖 路由分组

func middleware(c *fiber.Ctx) error {
	fmt.Println("Don't mind me!")
	return c.Next()
}

func handler(c *fiber.Ctx) error {
	return c.SendString(c.Path())
}

func main() {
	app := fiber.New()

	// Root API route
	api := app.Group("/api", middleware) // /api

	// API v1 routes
	v1 := api.Group("/v1", middleware) // /api/v1
	v1.Get("/list", handler)           // /api/v1/list
	v1.Get("/user", handler)           // /api/v1/user

	// API v2 routes
	v2 := api.Group("/v2", middleware) // /api/v2
	v2.Get("/list", handler)           // /api/v2/list
	v2.Get("/user", handler)           // /api/v2/user

	// ...
}

日志中间件

📖 Logger

package main

import (
	"log"

	"gitee.com/azhai/fiber-u8l"
	"gitee.com/azhai/fiber-u8l/middleware/logger"
)

func main() {
	app := fiber.New()

	app.Use(logger.New())

	// ...

	log.Fatal(app.Listen(":3000"))
}

跨域资源共享(CORS)中间件

📖 CORS

import (
	"log"

	"gitee.com/azhai/fiber-u8l"
	"gitee.com/azhai/fiber-u8l/middleware/cors"
)

func main() {
	app := fiber.New()

	app.Use(cors.New())

	// ...

	log.Fatal(app.Listen(":3000"))
}

通过在请求头中设置Origin传递任何域来检查CORS:

curl -H "Origin: http://example.com" --verbose http://localhost:3000

自定义404响应

📖 HTTP Methods

func main() {
	app := fiber.New()

	app.Static("/", "./public")

	app.Get("/demo", func(c *fiber.Ctx) error {
		return c.SendString("This is a demo!")
	})

	app.Post("/register", func(c *fiber.Ctx) error {
		return c.SendString("Welcome!")
	})

	// Last middleware to match anything
	app.Use(func(c *fiber.Ctx) error {
		return c.SendStatus(404)
		// => 404 "Not Found"
	})

	log.Fatal(app.Listen(":3000"))
}

JSON响应

📖 JSON

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	app := fiber.New()

	app.Get("/user", func(c *fiber.Ctx) error {
		return c.JSON(&User{"John", 20})
		// => {"name":"John", "age":20}
	})

	app.Get("/json", func(c *fiber.Ctx) error {
		return c.JSON(fiber.Map{
			"success": true,
			"message": "Hi John!",
		})
		// => {"success":true, "message":"Hi John!"}
	})

	log.Fatal(app.Listen(":3000"))
}

升级到WebSocket

📖 Websocket

import (
    "gitee.com/azhai/fiber-u8l"
    "github.com/gofiber/websocket"
)

func main() {
  app := fiber.New()

  app.Get("/ws", websocket.New(func(c *websocket.Conn) {
    for {
      mt, msg, err := c.ReadMessage()
      if err != nil {
        log.Println("read:", err)
        break
      }
      log.Printf("recv: %s", msg)
      err = c.WriteMessage(mt, msg)
      if err != nil {
        log.Println("write:", err)
        break
      }
    }
  }))

  log.Fatal(app.Listen(":3000"))
  // ws://localhost:3000/ws
}

恢复(panic)中间件

📖 Recover

import (
	"gitee.com/azhai/fiber-u8l"
	"gitee.com/azhai/fiber-u8l/recover"
)

func main() {
	app := fiber.New()

	app.Use(recover.New())

	app.Get("/", func(c *fiber.Ctx) error {
		panic("normally this would crash your app")
	})

	log.Fatal(app.Listen(":3000"))
}

🧬 Internal Middleware

Here is a list of middleware that are included within the Fiber framework.

Middleware Description
basicauth Basic auth middleware provides an HTTP basic authentication. It calls the next handler for valid credentials and 401 Unauthorized for missing or invalid credentials.
compress Compression middleware for Fiber, it supports deflate, gzip and brotli by default.
cors Enable cross-origin resource sharing (CORS) with various options.
csrf Protect from CSRF exploits.
filesystem FileSystem middleware for Fiber, special thanks and credits to Alireza Salary
favicon Ignore favicon from logs or serve from memory if a file path is provided.
limiter Rate-limiting middleware for Fiber. Use to limit repeated requests to public APIs and/or endpoints such as password reset.
logger HTTP request/response logger.
pprof Special thanks to Matthew Lee (@mthli)
recover Recover middleware recovers from panics anywhere in the stack chain and handles the control to the centralized ErrorHandler.

🧬 External Middleware

List of externally hosted middleware modules and maintained by the Fiber team.

Middleware Description
adaptor Converter for net/http handlers to/from Fiber request handlers, special thanks to @arsmn!
helmet Helps secure your apps by setting various HTTP headers.
jwt JWT returns a JSON Web Token (JWT) auth middleware.
keyauth Key auth middleware provides a key based authentication.
rewrite Rewrite middleware rewrites the URL path based on provided rules. It can be helpful for backward compatibility or just creating cleaner and more descriptive links.
session This session middleware is build on top of fasthttp/session by @savsgio MIT. Special thanks to @thomasvvugt for helping with this middleware.
template This package contains 8 template engines that can be used with Fiber v1.10.x Go version 1.13 or higher is required.
websocket Based on Fasthttp WebSocket for Fiber with Locals support!

🌱 第三方中间件

这是由Fiber社区创建的中间件列表,如果您想看到自己的中间件,请创建PR

👍 贡献

如果您要说声谢谢或支持Fiber的积极发展:

  1. FiberGitHub Star点个⭐星星。
  2. Twitter上发布有关项目的推文
  3. MediumDev.to或个人博客上写评论或教程。
  4. 通过捐赠一杯咖啡来支持本项目。

☕ 支持者

Fibre是一个开源项目,依靠捐赠来支付账单,例如我们的域名,gitbooknetlify和无服务器托管。如果要支持Fiber,可以 ☕ 在这里买一杯咖啡

User Donation
@destari ☕ x 10
@dembygenesis ☕ x 5
@thomasvvugt ☕ x 5
@hendratommy ☕ x 5
@ekaputra07 ☕ x 5
@jorgefuertes ☕ x 5
@candidosales ☕ x 5
@l0nax ☕ x 3
@ankush ☕ x 3
@bihe ☕ x 3
@justdave ☕ x 3
@koddr ☕ x 1
@lapolinar ☕ x 1
@diegowifi ☕ x 1
@ssimk0 ☕ x 1
@raymayemir ☕ x 1
@melkorm ☕ x 1
@marvinjwendt ☕ x 1
@toishy ☕ x 1

‎‍💻 Code Contributors

Code Contributors

⭐️ Stargazers

Stargazers over time

⚠️ License

Copyright (c) 2019-present Fenny and Contributors. Fiber is free and open-source software licensed under the MIT License. Official logo was created by Vic Shóstak and distributed under Creative Commons license (CC BY-SA 4.0 International).

Third-party library licenses

Documentation

Index

Constants

View Source
const (
	DefaultBodyLimit            = 4 * 1024 * 1024
	DefaultConcurrency          = 256 * 1024
	DefaultReadBufferSize       = 4096
	DefaultWriteBufferSize      = 4096
	DefaultCompressedFileSuffix = ".fiber.gz"
)

Default Config values

View Source
const (
	MethodGet     = "GET"     // RFC 7231, 4.3.1
	MethodHead    = "HEAD"    // RFC 7231, 4.3.2
	MethodPost    = "POST"    // RFC 7231, 4.3.3
	MethodPut     = "PUT"     // RFC 7231, 4.3.4
	MethodPatch   = "PATCH"   // RFC 5789
	MethodDelete  = "DELETE"  // RFC 7231, 4.3.5
	MethodConnect = "CONNECT" // RFC 7231, 4.3.6
	MethodOptions = "OPTIONS" // RFC 7231, 4.3.7
	MethodTrace   = "TRACE"   // RFC 7231, 4.3.8

)

HTTP methods were copied from net/http.

View Source
const (
	MIMETextXML               = "text/xml"
	MIMETextHTML              = "text/html"
	MIMETextPlain             = "text/plain"
	MIMEApplicationXML        = "application/xml"
	MIMEApplicationJSON       = "application/json"
	MIMEApplicationJavaScript = "application/javascript"
	MIMEApplicationForm       = "application/x-www-form-urlencoded"
	MIMEOctetStream           = "application/octet-stream"
	MIMEMultipartForm         = "multipart/form-data"

	MIMETextXMLCharsetUTF8               = "text/xml; charset=utf-8"
	MIMETextHTMLCharsetUTF8              = "text/html; charset=utf-8"
	MIMETextPlainCharsetUTF8             = "text/plain; charset=utf-8"
	MIMEApplicationXMLCharsetUTF8        = "application/xml; charset=utf-8"
	MIMEApplicationJSONCharsetUTF8       = "application/json; charset=utf-8"
	MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8"
)

MIME types that are commonly used

View Source
const (
	StatusContinue                      = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols            = 101 // RFC 7231, 6.2.2
	StatusProcessing                    = 102 // RFC 2518, 10.1
	StatusEarlyHints                    = 103 // RFC 8297
	StatusOK                            = 200 // RFC 7231, 6.3.1
	StatusCreated                       = 201 // RFC 7231, 6.3.2
	StatusAccepted                      = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInformation   = 203 // RFC 7231, 6.3.4
	StatusNoContent                     = 204 // RFC 7231, 6.3.5
	StatusResetContent                  = 205 // RFC 7231, 6.3.6
	StatusPartialContent                = 206 // RFC 7233, 4.1
	StatusMultiStatus                   = 207 // RFC 4918, 11.1
	StatusAlreadyReported               = 208 // RFC 5842, 7.1
	StatusIMUsed                        = 226 // RFC 3229, 10.4.1
	StatusMultipleChoices               = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently              = 301 // RFC 7231, 6.4.2
	StatusFound                         = 302 // RFC 7231, 6.4.3
	StatusSeeOther                      = 303 // RFC 7231, 6.4.4
	StatusNotModified                   = 304 // RFC 7232, 4.1
	StatusUseProxy                      = 305 // RFC 7231, 6.4.5
	StatusTemporaryRedirect             = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect             = 308 // RFC 7538, 3
	StatusBadRequest                    = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                  = 401 // RFC 7235, 3.1
	StatusPaymentRequired               = 402 // RFC 7231, 6.5.2
	StatusForbidden                     = 403 // RFC 7231, 6.5.3
	StatusNotFound                      = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed              = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                 = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired             = 407 // RFC 7235, 3.2
	StatusRequestTimeout                = 408 // RFC 7231, 6.5.7
	StatusConflict                      = 409 // RFC 7231, 6.5.8
	StatusGone                          = 410 // RFC 7231, 6.5.9
	StatusLengthRequired                = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed            = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge         = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong             = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType          = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable  = 416 // RFC 7233, 4.4
	StatusExpectationFailed             = 417 // RFC 7231, 6.5.14
	StatusTeapot                        = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest            = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity           = 422 // RFC 4918, 11.2
	StatusLocked                        = 423 // RFC 4918, 11.3
	StatusFailedDependency              = 424 // RFC 4918, 11.4
	StatusTooEarly                      = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired               = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired          = 428 // RFC 6585, 3
	StatusTooManyRequests               = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge   = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons    = 451 // RFC 7725, 3
	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes were copied from net/http.

View Source
const (
	HeaderAuthorization                   = "Authorization"
	HeaderProxyAuthenticate               = "Proxy-Authenticate"
	HeaderProxyAuthorization              = "Proxy-Authorization"
	HeaderWWWAuthenticate                 = "WWW-Authenticate"
	HeaderAge                             = "Age"
	HeaderCacheControl                    = "Cache-Control"
	HeaderClearSiteData                   = "Clear-Site-Data"
	HeaderExpires                         = "Expires"
	HeaderPragma                          = "Pragma"
	HeaderWarning                         = "Warning"
	HeaderAcceptCH                        = "Accept-CH"
	HeaderAcceptCHLifetime                = "Accept-CH-Lifetime"
	HeaderContentDPR                      = "Content-DPR"
	HeaderDPR                             = "DPR"
	HeaderEarlyData                       = "Early-Data"
	HeaderSaveData                        = "Save-Data"
	HeaderViewportWidth                   = "Viewport-Width"
	HeaderWidth                           = "Width"
	HeaderETag                            = "ETag"
	HeaderIfMatch                         = "If-Match"
	HeaderIfModifiedSince                 = "If-Modified-Since"
	HeaderIfNoneMatch                     = "If-None-Match"
	HeaderIfUnmodifiedSince               = "If-Unmodified-Since"
	HeaderLastModified                    = "Last-Modified"
	HeaderVary                            = "Vary"
	HeaderConnection                      = "Connection"
	HeaderKeepAlive                       = "Keep-Alive"
	HeaderAccept                          = "Accept"
	HeaderAcceptCharset                   = "Accept-Charset"
	HeaderAcceptEncoding                  = "Accept-Encoding"
	HeaderAcceptLanguage                  = "Accept-Language"
	HeaderCookie                          = "Cookie"
	HeaderExpect                          = "Expect"
	HeaderMaxForwards                     = "Max-Forwards"
	HeaderSetCookie                       = "Set-Cookie"
	HeaderAccessControlAllowCredentials   = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders       = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods       = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin        = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders      = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge             = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders     = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod      = "Access-Control-Request-Method"
	HeaderOrigin                          = "Origin"
	HeaderTimingAllowOrigin               = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies   = "X-Permitted-Cross-Domain-Policies"
	HeaderDNT                             = "DNT"
	HeaderTk                              = "Tk"
	HeaderContentDisposition              = "Content-Disposition"
	HeaderContentEncoding                 = "Content-Encoding"
	HeaderContentLanguage                 = "Content-Language"
	HeaderContentLength                   = "Content-Length"
	HeaderContentLocation                 = "Content-Location"
	HeaderContentType                     = "Content-Type"
	HeaderForwarded                       = "Forwarded"
	HeaderVia                             = "Via"
	HeaderXForwardedFor                   = "X-Forwarded-For"
	HeaderXForwardedHost                  = "X-Forwarded-Host"
	HeaderXForwardedProto                 = "X-Forwarded-Proto"
	HeaderXForwardedProtocol              = "X-Forwarded-Protocol"
	HeaderXForwardedSsl                   = "X-Forwarded-Ssl"
	HeaderXUrlScheme                      = "X-Url-Scheme"
	HeaderLocation                        = "Location"
	HeaderFrom                            = "From"
	HeaderHost                            = "Host"
	HeaderReferer                         = "Referer"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderUserAgent                       = "User-Agent"
	HeaderAllow                           = "Allow"
	HeaderServer                          = "Server"
	HeaderAcceptRanges                    = "Accept-Ranges"
	HeaderContentRange                    = "Content-Range"
	HeaderIfRange                         = "If-Range"
	HeaderRange                           = "Range"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        = "Expect-CT"
	// Deprecated: use HeaderPermissionsPolicy instead
	HeaderFeaturePolicy           = "Feature-Policy"
	HeaderPermissionsPolicy       = "Permissions-Policy"
	HeaderPublicKeyPins           = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXDownloadOptions        = "X-Download-Options"
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderXPoweredBy              = "X-Powered-By"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderLastEventID             = "Last-Event-ID"
	HeaderNEL                     = "NEL"
	HeaderPingFrom                = "Ping-From"
	HeaderPingTo                  = "Ping-To"
	HeaderReportTo                = "Report-To"
	HeaderTE                      = "TE"
	HeaderTrailer                 = "Trailer"
	HeaderTransferEncoding        = "Transfer-Encoding"
	HeaderSecWebSocketAccept      = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions  = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey         = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol    = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion     = "Sec-WebSocket-Version"
	HeaderAcceptPatch             = "Accept-Patch"
	HeaderAcceptPushPolicy        = "Accept-Push-Policy"
	HeaderAcceptSignature         = "Accept-Signature"
	HeaderAltSvc                  = "Alt-Svc"
	HeaderDate                    = "Date"
	HeaderIndex                   = "Index"
	HeaderLargeAllocation         = "Large-Allocation"
	HeaderLink                    = "Link"
	HeaderPushPolicy              = "Push-Policy"
	HeaderRetryAfter              = "Retry-After"
	HeaderServerTiming            = "Server-Timing"
	HeaderSignature               = "Signature"
	HeaderSignedHeaders           = "Signed-Headers"
	HeaderSourceMap               = "SourceMap"
	HeaderUpgrade                 = "Upgrade"
	HeaderXDNSPrefetchControl     = "X-DNS-Prefetch-Control"
	HeaderXPingback               = "X-Pingback"
	HeaderXRequestID              = "X-Request-ID"
	HeaderXRequestedWith          = "X-Requested-With"
	HeaderXRobotsTag              = "X-Robots-Tag"
	HeaderXUACompatible           = "X-UA-Compatible"
)

HTTP Headers were copied from net/http.

View Source
const (
	NetworkTCP  = "tcp"
	NetworkTCP4 = "tcp4"
	NetworkTCP6 = "tcp6"
)

Network types that are commonly used

View Source
const (
	StrGzip    = "gzip"
	StrBr      = "br"
	StrDeflate = "deflate"
	StrBrotli  = "brotli"
)

Compression types

View Source
const (
	CookieSameSiteDisabled   = "disabled" // not in RFC, just control "SameSite" attribute will not be set.
	CookieSameSiteLaxMode    = "lax"
	CookieSameSiteStrictMode = "strict"
	CookieSameSiteNoneMode   = "none"
)

Cookie SameSite https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7

View Source
const (
	COOKIE_TOKEN_KEY = "access_token"
	HEADER_TOKEN_KEY = "x-token"
)
View Source
const Version = "1.26.0"

Version of current fiber package

Variables

View Source
var (
	ErrRangeMalformed     = errors.New("range: malformed range header string")
	ErrRangeUnsatisfiable = errors.New("range: unsatisfiable range")
)
View Source
var (
	ErrBadRequest                    = NewError(StatusBadRequest)                    // RFC 7231, 6.5.1
	ErrUnauthorized                  = NewError(StatusUnauthorized)                  // RFC 7235, 3.1
	ErrPaymentRequired               = NewError(StatusPaymentRequired)               // RFC 7231, 6.5.2
	ErrForbidden                     = NewError(StatusForbidden)                     // RFC 7231, 6.5.3
	ErrNotFound                      = NewError(StatusNotFound)                      // RFC 7231, 6.5.4
	ErrMethodNotAllowed              = NewError(StatusMethodNotAllowed)              // RFC 7231, 6.5.5
	ErrNotAcceptable                 = NewError(StatusNotAcceptable)                 // RFC 7231, 6.5.6
	ErrProxyAuthRequired             = NewError(StatusProxyAuthRequired)             // RFC 7235, 3.2
	ErrRequestTimeout                = NewError(StatusRequestTimeout)                // RFC 7231, 6.5.7
	ErrConflict                      = NewError(StatusConflict)                      // RFC 7231, 6.5.8
	ErrGone                          = NewError(StatusGone)                          // RFC 7231, 6.5.9
	ErrLengthRequired                = NewError(StatusLengthRequired)                // RFC 7231, 6.5.10
	ErrPreconditionFailed            = NewError(StatusPreconditionFailed)            // RFC 7232, 4.2
	ErrRequestEntityTooLarge         = NewError(StatusRequestEntityTooLarge)         // RFC 7231, 6.5.11
	ErrRequestURITooLong             = NewError(StatusRequestURITooLong)             // RFC 7231, 6.5.12
	ErrUnsupportedMediaType          = NewError(StatusUnsupportedMediaType)          // RFC 7231, 6.5.13
	ErrRequestedRangeNotSatisfiable  = NewError(StatusRequestedRangeNotSatisfiable)  // RFC 7233, 4.4
	ErrExpectationFailed             = NewError(StatusExpectationFailed)             // RFC 7231, 6.5.14
	ErrTeapot                        = NewError(StatusTeapot)                        // RFC 7168, 2.3.3
	ErrMisdirectedRequest            = NewError(StatusMisdirectedRequest)            // RFC 7540, 9.1.2
	ErrUnprocessableEntity           = NewError(StatusUnprocessableEntity)           // RFC 4918, 11.2
	ErrLocked                        = NewError(StatusLocked)                        // RFC 4918, 11.3
	ErrFailedDependency              = NewError(StatusFailedDependency)              // RFC 4918, 11.4
	ErrTooEarly                      = NewError(StatusTooEarly)                      // RFC 8470, 5.2.
	ErrUpgradeRequired               = NewError(StatusUpgradeRequired)               // RFC 7231, 6.5.15
	ErrPreconditionRequired          = NewError(StatusPreconditionRequired)          // RFC 6585, 3
	ErrTooManyRequests               = NewError(StatusTooManyRequests)               // RFC 6585, 4
	ErrRequestHeaderFieldsTooLarge   = NewError(StatusRequestHeaderFieldsTooLarge)   // RFC 6585, 5
	ErrUnavailableForLegalReasons    = NewError(StatusUnavailableForLegalReasons)    // RFC 7725, 3
	ErrInternalServerError           = NewError(StatusInternalServerError)           // RFC 7231, 6.6.1
	ErrNotImplemented                = NewError(StatusNotImplemented)                // RFC 7231, 6.6.2
	ErrBadGateway                    = NewError(StatusBadGateway)                    // RFC 7231, 6.6.3
	ErrServiceUnavailable            = NewError(StatusServiceUnavailable)            // RFC 7231, 6.6.4
	ErrGatewayTimeout                = NewError(StatusGatewayTimeout)                // RFC 7231, 6.6.5
	ErrHTTPVersionNotSupported       = NewError(StatusHTTPVersionNotSupported)       // RFC 7231, 6.6.6
	ErrVariantAlsoNegotiates         = NewError(StatusVariantAlsoNegotiates)         // RFC 2295, 8.1
	ErrInsufficientStorage           = NewError(StatusInsufficientStorage)           // RFC 4918, 11.5
	ErrLoopDetected                  = NewError(StatusLoopDetected)                  // RFC 5842, 7.2
	ErrNotExtended                   = NewError(StatusNotExtended)                   // RFC 2774, 7
	ErrNetworkAuthenticationRequired = NewError(StatusNetworkAuthenticationRequired) // RFC 6585, 6
)

Errors

View Source
var DefaultErrorHandler = func(c *Ctx, err error) error {
	code := StatusInternalServerError
	if e, ok := err.(*Error); ok {
		code = e.Code
	}
	c.Set(HeaderContentType, MIMETextPlainCharsetUTF8)
	return c.Status(code).SendString(err.Error())
}

DefaultErrorHandler that process return errors from handlers

Functions

func FirstFloatArg added in v1.20.1

func FirstFloatArg(args []float64) float64

func FirstIntArg added in v1.20.1

func FirstIntArg(args []int) int

func FirstStrArg added in v1.20.1

func FirstStrArg(args []string) string

func GetServiceCode added in v1.10.91

func GetServiceCode(statusCode int) int

func GetTrimmedParam added in v1.20.1

func GetTrimmedParam(param string) string

GetTrimmedParam trims the ':' & '?' from a string

func IsChild added in v1.20.1

func IsChild() bool

IsChild determines if the current process is a child of Prefork

func PeekForm added in v1.10.5

func PeekForm(key string, mf *multipart.Form, err error) string

func ReleaseAgent added in v1.26.0

func ReleaseAgent(a *Agent)

ReleaseAgent returns a acquired via AcquireAgent to Agent pool.

It is forbidden accessing req and/or its' members after returning it to Agent pool.

func ReleaseArgs added in v1.26.0

func ReleaseArgs(a *Args)

ReleaseArgs returns the object acquired via AcquireArgs to the pool.

String not access the released Args object, otherwise data races may occur. Copy from fasthttp

func ReleaseClient added in v1.26.0

func ReleaseClient(c *Client)

ReleaseClient returns c acquired via AcquireClient to client pool.

It is forbidden accessing req and/or its' members after returning it to client pool.

func ReleaseFormFile added in v1.26.0

func ReleaseFormFile(ff *FormFile)

ReleaseFormFile returns the object acquired via AcquireFormFile to the pool.

String not access the released FormFile object, otherwise data races may occur.

func ReleaseResponse added in v1.26.0

func ReleaseResponse(resp *Response)

ReleaseResponse return resp acquired via AcquireResponse to response pool.

It is forbidden accessing resp and/or its' members after returning it to response pool. Copy from fasthttp

func RemoveEscapeChar added in v1.28.0

func RemoveEscapeChar(word string) string

RemoveEscapeChar remove escape characters

Types

type Agent added in v1.26.0

type Agent struct {
	// Name is used in User-Agent request header.
	Name string

	// NoDefaultUserAgentHeader when set to true, causes the default
	// User-Agent header to be excluded from the Request.
	NoDefaultUserAgentHeader bool

	// HostClient is an embedded fasthttp HostClient
	*fasthttp.HostClient
	// contains filtered or unexported fields
}

Agent is an object storing all request data for client. Agent instance MUST NOT be used from concurrently running goroutines.

func AcquireAgent added in v1.26.0

func AcquireAgent() *Agent

AcquireAgent returns an empty Agent instance from Agent pool.

The returned Agent instance may be passed to ReleaseAgent when it is no longer needed. This allows Agent recycling, reduces GC pressure and usually improves performance.

func Delete added in v1.26.0

func Delete(url string) *Agent

Delete sends DELETE request to the given url.

func Get added in v1.26.0

func Get(url string) *Agent

Get returns a agent with http method GET.

func Head(url string) *Agent

Head returns a agent with http method HEAD.

func Patch added in v1.26.0

func Patch(url string) *Agent

Patch sends PATCH request to the given url.

func Post added in v1.26.0

func Post(url string) *Agent

Post sends POST request to the given url.

func Put added in v1.26.0

func Put(url string) *Agent

Put sends PUT request to the given url.

func (*Agent) Add added in v1.26.0

func (a *Agent) Add(k, v string) *Agent

Add adds the given 'key: value' header.

Multiple headers with the same key may be added with this function. Use Set for setting a single header for the given key.

func (*Agent) AddBytesK added in v1.26.0

func (a *Agent) AddBytesK(k []byte, v string) *Agent

AddBytesK adds the given 'key: value' header.

Multiple headers with the same key may be added with this function. Use SetBytesK for setting a single header for the given key.

func (*Agent) AddBytesKV added in v1.26.0

func (a *Agent) AddBytesKV(k []byte, v []byte) *Agent

AddBytesKV adds the given 'key: value' header.

Multiple headers with the same key may be added with this function. Use SetBytesKV for setting a single header for the given key.

func (*Agent) AddBytesV added in v1.26.0

func (a *Agent) AddBytesV(k string, v []byte) *Agent

AddBytesV adds the given 'key: value' header.

Multiple headers with the same key may be added with this function. Use SetBytesV for setting a single header for the given key.

func (*Agent) BasicAuth added in v1.26.0

func (a *Agent) BasicAuth(username, password string) *Agent

BasicAuth sets URI username and password.

func (*Agent) BasicAuthBytes added in v1.26.0

func (a *Agent) BasicAuthBytes(username, password []byte) *Agent

BasicAuthBytes sets URI username and password.

func (*Agent) Body added in v1.26.0

func (a *Agent) Body(body []byte) *Agent

Body sets request body.

func (*Agent) BodyStream added in v1.26.0

func (a *Agent) BodyStream(bodyStream io.Reader, bodySize int) *Agent

BodyStream sets request body stream and, optionally body size.

If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes before returning io.EOF.

If bodySize < 0, then bodyStream is read until io.EOF.

bodyStream.Close() is called after finishing reading all body data if it implements io.Closer.

Note that GET and HEAD requests cannot have body.

func (*Agent) BodyString added in v1.26.0

func (a *Agent) BodyString(bodyString string) *Agent

BodyString sets request body.

func (*Agent) Boundary added in v1.26.0

func (a *Agent) Boundary(boundary string) *Agent

Boundary sets boundary for multipart form request.

func (*Agent) Bytes added in v1.26.0

func (a *Agent) Bytes() (code int, body []byte, errs []error)

Bytes returns the status code, bytes body and errors of url.

func (*Agent) ConnectionClose added in v1.26.0

func (a *Agent) ConnectionClose() *Agent

ConnectionClose sets 'Connection: close' header.

func (*Agent) ContentType added in v1.26.0

func (a *Agent) ContentType(contentType string) *Agent

ContentType sets Content-Type header value.

func (*Agent) ContentTypeBytes added in v1.26.0

func (a *Agent) ContentTypeBytes(contentType []byte) *Agent

ContentTypeBytes sets Content-Type header value.

func (*Agent) Cookie added in v1.26.0

func (a *Agent) Cookie(key, value string) *Agent

Cookie sets one 'key: value' cookie.

func (*Agent) CookieBytesK added in v1.26.0

func (a *Agent) CookieBytesK(key []byte, value string) *Agent

CookieBytesK sets one 'key: value' cookie.

func (*Agent) CookieBytesKV added in v1.26.0

func (a *Agent) CookieBytesKV(key, value []byte) *Agent

CookieBytesKV sets one 'key: value' cookie.

func (*Agent) Cookies added in v1.26.0

func (a *Agent) Cookies(kv ...string) *Agent

Cookies sets multiple 'key: value' cookies.

func (*Agent) CookiesBytesKV added in v1.26.0

func (a *Agent) CookiesBytesKV(kv ...[]byte) *Agent

CookiesBytesKV sets multiple 'key: value' cookies.

func (*Agent) Debug added in v1.26.0

func (a *Agent) Debug(w ...io.Writer) *Agent

Debug mode enables logging request and response detail

func (*Agent) Dest added in v1.26.0

func (a *Agent) Dest(dest []byte) *Agent

Dest sets custom dest.

The contents of dest will be replaced by the response body, if the dest is too small a new slice will be allocated.

func (*Agent) FileData added in v1.26.0

func (a *Agent) FileData(formFiles ...*FormFile) *Agent

FileData appends files for multipart form request.

It is recommended obtaining formFile via AcquireFormFile and release it manually in performance-critical code.

func (*Agent) Form added in v1.26.0

func (a *Agent) Form(args *Args) *Agent

Form sends form request with body if args is non-nil.

It is recommended obtaining args via AcquireArgs and release it manually in performance-critical code.

func (*Agent) Host added in v1.26.0

func (a *Agent) Host(host string) *Agent

Host sets host for the uri.

func (*Agent) HostBytes added in v1.26.0

func (a *Agent) HostBytes(host []byte) *Agent

HostBytes sets host for the URI.

func (*Agent) InsecureSkipVerify added in v1.26.0

func (a *Agent) InsecureSkipVerify() *Agent

InsecureSkipVerify controls whether the Agent verifies the server certificate chain and host name.

func (*Agent) JSON added in v1.26.0

func (a *Agent) JSON(v interface{}) *Agent

JSON sends a JSON request.

func (*Agent) JSONDecoder added in v1.26.0

func (a *Agent) JSONDecoder(jsonDecoder utils.JSONUnmarshal) *Agent

JSONDecoder sets custom json decoder.

func (*Agent) JSONEncoder added in v1.26.0

func (a *Agent) JSONEncoder(jsonEncoder utils.JSONMarshal) *Agent

JSONEncoder sets custom json encoder.

func (*Agent) MaxRedirectsCount added in v1.26.0

func (a *Agent) MaxRedirectsCount(count int) *Agent

MaxRedirectsCount sets max redirect count for GET and HEAD.

func (*Agent) MultipartForm added in v1.26.0

func (a *Agent) MultipartForm(args *Args) *Agent

MultipartForm sends multipart form request with k-v and files.

It is recommended obtaining args via AcquireArgs and release it manually in performance-critical code.

func (*Agent) Parse added in v1.26.0

func (a *Agent) Parse() error

Parse initializes URI and HostClient.

func (*Agent) QueryString added in v1.26.0

func (a *Agent) QueryString(queryString string) *Agent

QueryString sets URI query string.

func (*Agent) QueryStringBytes added in v1.26.0

func (a *Agent) QueryStringBytes(queryString []byte) *Agent

QueryStringBytes sets URI query string.

func (*Agent) Referer added in v1.26.0

func (a *Agent) Referer(referer string) *Agent

Referer sets Referer header value.

func (*Agent) RefererBytes added in v1.26.0

func (a *Agent) RefererBytes(referer []byte) *Agent

RefererBytes sets Referer header value.

func (*Agent) Request added in v1.26.0

func (a *Agent) Request() *Request

Request returns Agent request instance.

func (*Agent) Reuse added in v1.26.0

func (a *Agent) Reuse() *Agent

Reuse enables the Agent instance to be used again after one request.

If agent is reusable, then it should be released manually when it is no longer used.

func (*Agent) SendFile added in v1.26.0

func (a *Agent) SendFile(filename string, fieldname ...string) *Agent

SendFile reads file and appends it to multipart form request.

func (*Agent) SendFiles added in v1.26.0

func (a *Agent) SendFiles(filenamesAndFieldnames ...string) *Agent

SendFiles reads files and appends them to multipart form request.

Examples:

SendFile("/path/to/file1", "fieldname1", "/path/to/file2")

func (*Agent) Set added in v1.26.0

func (a *Agent) Set(k, v string) *Agent

Set sets the given 'key: value' header.

Use Add for setting multiple header values under the same key.

func (*Agent) SetBytesK added in v1.26.0

func (a *Agent) SetBytesK(k []byte, v string) *Agent

SetBytesK sets the given 'key: value' header.

Use AddBytesK for setting multiple header values under the same key.

func (*Agent) SetBytesKV added in v1.26.0

func (a *Agent) SetBytesKV(k []byte, v []byte) *Agent

SetBytesKV sets the given 'key: value' header.

Use AddBytesKV for setting multiple header values under the same key.

func (*Agent) SetBytesV added in v1.26.0

func (a *Agent) SetBytesV(k string, v []byte) *Agent

SetBytesV sets the given 'key: value' header.

Use AddBytesV for setting multiple header values under the same key.

func (*Agent) SetResponse added in v1.26.0

func (a *Agent) SetResponse(customResp *Response) *Agent

SetResponse sets custom response for the Agent instance.

It is recommended obtaining custom response via AcquireResponse and release it manually in performance-critical code.

func (*Agent) String added in v1.26.0

func (a *Agent) String() (int, string, []error)

String returns the status code, string body and errors of url.

func (*Agent) Struct added in v1.26.0

func (a *Agent) Struct(v interface{}) (code int, body []byte, errs []error)

Struct returns the status code, bytes body and errors of url. And bytes body will be unmarshalled to given v.

func (*Agent) TLSConfig added in v1.26.0

func (a *Agent) TLSConfig(config *tls.Config) *Agent

TLSConfig sets tls config.

func (*Agent) Timeout added in v1.26.0

func (a *Agent) Timeout(timeout time.Duration) *Agent

Timeout sets request timeout duration.

func (*Agent) UserAgent added in v1.26.0

func (a *Agent) UserAgent(userAgent string) *Agent

UserAgent sets User-Agent header value.

func (*Agent) UserAgentBytes added in v1.26.0

func (a *Agent) UserAgentBytes(userAgent []byte) *Agent

UserAgentBytes sets User-Agent header value.

func (*Agent) XML added in v1.26.0

func (a *Agent) XML(v interface{}) *Agent

XML sends an XML request.

type App

type App struct {
	// contains filtered or unexported fields
}

App denotes the Fiber application.

func New

func New(config ...Config) *App

New creates a new Fiber named instance.

app := fiber.New()

You can pass optional configuration options by passing a Config struct:

app := fiber.New(fiber.Config{
    Prefork: true,
    ServerHeader: "Fiber",
})

func (*App) AcquireCtx added in v1.10.91

func (app *App) AcquireCtx(fctx *fasthttp.RequestCtx) *Ctx

AcquireCtx retrieves a new Ctx from the pool.

func (*App) Add

func (app *App) Add(method, path string, handlers ...Handler) Router

Add allows you to specify a HTTP method to register a route

func (*App) All

func (app *App) All(path string, handlers ...Handler) Router

All will register the handler on all HTTP methods

func (*App) Config added in v1.20.1

func (app *App) Config() Config

Config returns the app config as value ( read-only ).

func (*App) Connect

func (app *App) Connect(path string, handlers ...Handler) Router

Connect registers a route for CONNECT methods that establishes a tunnel to the server identified by the target resource.

func (*App) Delete

func (app *App) Delete(path string, handlers ...Handler) Router

Delete registers a route for DELETE methods that deletes the specified resource.

func (*App) Get

func (app *App) Get(path string, handlers ...Handler) Router

Get registers a route for GET methods that requests a representation of the specified resource. Requests using GET should only retrieve data.

func (*App) Group

func (app *App) Group(prefix string, handlers ...Handler) Router

Group is used for Routes with common prefix to define a new sub-router with optional middleware.

api := app.Group("/api")
api.Get("/users", handler)

func (*App) Handler added in v1.20.1

func (app *App) Handler() fasthttp.RequestHandler

Handler returns the server handler.

func (*App) Head

func (app *App) Head(path string, handlers ...Handler) Router

Head registers a route for HEAD methods that asks for a response identical to that of a GET request, but without the response body.

func (*App) Listen

func (app *App) Listen(addr string) error

Listen serves HTTP requests from the given addr.

app.Listen(":8080")
app.Listen("127.0.0.1:8080")

func (*App) ListenTLS added in v1.23.3

func (app *App) ListenTLS(addr, certFile, keyFile string) error

app.ListenTLS(":8080", "./cert.pem", "./cert.key") app.ListenTLS(":8080", "./cert.pem", "./cert.key")

func (*App) Listener added in v1.20.1

func (app *App) Listener(ln net.Listener) error

Listener can be used to pass a custom listener.

func (*App) Mount added in v1.10.1

func (app *App) Mount(prefix string, fiber *App) Router

Mount attaches another app instance as a sub-router along a routing path. It's very useful to split up a large API as many independent routers and compose them as a single service using Mount.

func (*App) Options

func (app *App) Options(path string, handlers ...Handler) Router

Options registers a route for OPTIONS methods that is used to describe the communication options for the target resource.

func (*App) Patch

func (app *App) Patch(path string, handlers ...Handler) Router

Patch registers a route for PATCH methods that is used to apply partial modifications to a resource.

func (*App) Post

func (app *App) Post(path string, handlers ...Handler) Router

Post registers a route for POST methods that is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

func (*App) Put

func (app *App) Put(path string, handlers ...Handler) Router

Put registers a route for PUT methods that replaces all current representations of the target resource with the request payload.

func (*App) ReleaseCtx added in v1.10.91

func (app *App) ReleaseCtx(c *Ctx)

ReleaseCtx releases the ctx back into the pool.

func (*App) Server added in v1.20.3

func (app *App) Server() *fasthttp.Server

Server returns the underlying fasthttp server

func (*App) Shutdown

func (app *App) Shutdown() error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle and then shut down.

Make sure the program doesn't exit and waits instead for Shutdown to return.

Shutdown does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.

func (*App) Stack added in v1.20.1

func (app *App) Stack() [][]*Route

Stack returns the raw router stack.

func (*App) Static

func (app *App) Static(prefix, root string, config ...Static) Router

Static will create a file server serving static files

func (*App) Test

func (app *App) Test(req *http.Request, msTimeout ...int) (resp *http.Response, err error)

Test is used for internal debugging by passing a *http.Request. Timeout is optional and defaults to 1s, -1 will disable it completely.

func (*App) Trace

func (app *App) Trace(path string, handlers ...Handler) Router

Trace registers a route for TRACE methods that performs a message loop-back test along the path to the target resource.

func (*App) Use

func (app *App) Use(args ...interface{}) Router

Use registers a middleware route that will match requests with the provided prefix (which is optional and defaults to "/").

app.Use(func(c *fiber.Ctx) error {
     return c.Next()
})
app.Use("/api", func(c *fiber.Ctx) error {
     return c.Next()
})
app.Use("/api", handler, func(c *fiber.Ctx) error {
     return c.Next()
})

This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...

type Args added in v1.26.0

type Args = fasthttp.Args

Args represents query arguments.

It is forbidden copying Args instances. Create new instances instead and use CopyTo().

Args instance MUST NOT be used from concurrently running goroutines. Copy from fasthttp

func AcquireArgs added in v1.26.0

func AcquireArgs() *Args

AcquireArgs returns an empty Args object from the pool.

The returned Args may be returned to the pool with ReleaseArgs when no longer needed. This allows reducing GC load. Copy from fasthttp

type Client added in v1.26.0

type Client struct {
	// UserAgent is used in User-Agent request header.
	UserAgent string

	// NoDefaultUserAgentHeader when set to true, causes the default
	// User-Agent header to be excluded from the Request.
	NoDefaultUserAgentHeader bool

	// When set by an external client of Fiber it will use the provided implementation of a
	// JSONMarshal
	//
	// Allowing for flexibility in using another json library for encoding
	JSONEncoder utils.JSONMarshal

	// When set by an external client of Fiber it will use the provided implementation of a
	// JSONUnmarshal
	//
	// Allowing for flexibility in using another json library for decoding
	JSONDecoder utils.JSONUnmarshal
}

Client implements http client.

It is safe calling Client methods from concurrently running goroutines.

func AcquireClient added in v1.26.0

func AcquireClient() *Client

AcquireClient returns an empty Client instance from client pool.

The returned Client instance may be passed to ReleaseClient when it is no longer needed. This allows Client recycling, reduces GC pressure and usually improves performance.

func (*Client) Delete added in v1.26.0

func (c *Client) Delete(url string) *Agent

Delete sends DELETE request to the given url.

func (*Client) Get added in v1.26.0

func (c *Client) Get(url string) *Agent

Get returns a agent with http method GET.

func (*Client) Head added in v1.26.0

func (c *Client) Head(url string) *Agent

Head returns a agent with http method GET.

func (*Client) Patch added in v1.26.0

func (c *Client) Patch(url string) *Agent

Patch sends PATCH request to the given url.

func (*Client) Post added in v1.26.0

func (c *Client) Post(url string) *Agent

Post sends POST request to the given url.

func (*Client) Put added in v1.26.0

func (c *Client) Put(url string) *Agent

Put sends PUT request to the given url.

type Config added in v1.20.1

type Config struct {
	// When set to true, this will spawn multiple Go processes listening on the same port.
	//
	// Default: false
	Prefork bool `json:"prefork"`

	// Enables the "Server: value" HTTP header.
	//
	// Default: ""
	ServerHeader string `json:"server_header"`

	// When set to true, the router treats "/foo" and "/foo/" as different.
	// By default this is disabled and both "/foo" and "/foo/" will execute the same handler.
	//
	// Default: false
	StrictRouting bool `json:"strict_routing"`

	// When set to true, enables case sensitive routing.
	// E.g. "/FoO" and "/foo" are treated as different routes.
	// By default this is disabled and both "/FoO" and "/foo" will execute the same handler.
	//
	// Default: false
	CaseSensitive bool `json:"case_sensitive"`

	// When set to true, this relinquishes the 0-allocation promise in certain
	// cases in order to access the handler values (e.g. request bodies) in an
	// immutable fashion so that these values are available even if you return
	// from handler.
	//
	// Default: false
	Immutable bool `json:"immutable"`

	// When set to true, converts all encoded characters in the route back
	// before setting the path for the context, so that the routing,
	// the returning of the current url from the context `ctx.Path()`
	// and the parameters `ctx.Params(%key%)` with decoded characters will work
	//
	// Default: false
	UnescapePath bool `json:"unescape_path"`

	// Enable or disable ETag header generation, since both weak and strong etags are generated
	// using the same hashing method (CRC-32). Weak ETags are the default when enabled.
	//
	// Default: false
	ETag bool `json:"etag"`

	// Max body size that the server accepts.
	// -1 will decline any body size
	//
	// Default: 4 * 1024 * 1024
	BodyLimit int `json:"body_limit"`

	// Maximum number of concurrent connections.
	//
	// Default: 256 * 1024
	Concurrency int `json:"concurrency"`

	// Views is the interface that wraps the Render function.
	//
	// Default: nil
	Views Views `json:"-"`

	// Views Layout is the global layout for all template render until override on Render function.
	//
	// Default: ""
	ViewsLayout string `json:"views_layout"`

	// The amount of time allowed to read the full request including body.
	// It is reset after the request handler has returned.
	// The connection's read deadline is reset when the connection opens.
	//
	// Default: unlimited
	ReadTimeout time.Duration `json:"read_timeout"`

	// The maximum duration before timing out writes of the response.
	// It is reset after the request handler has returned.
	//
	// Default: unlimited
	WriteTimeout time.Duration `json:"write_timeout"`

	// The maximum amount of time to wait for the next request when keep-alive is enabled.
	// If IdleTimeout is zero, the value of ReadTimeout is used.
	//
	// Default: unlimited
	IdleTimeout time.Duration `json:"idle_timeout"`

	// Per-connection buffer size for requests' reading.
	// This also limits the maximum header size.
	// Increase this buffer if your clients send multi-KB RequestURIs
	// and/or multi-KB headers (for example, BIG cookies).
	//
	// Default: 4096
	ReadBufferSize int `json:"read_buffer_size"`

	// Per-connection buffer size for responses' writing.
	//
	// Default: 4096
	WriteBufferSize int `json:"write_buffer_size"`

	// CompressedFileSuffix adds suffix to the original file name and
	// tries saving the resulting compressed file under the new file name.
	//
	// Default: ".fiber.gz"
	CompressedFileSuffix string `json:"compressed_file_suffix"`

	// ProxyHeader will enable c.IP() to return the value of the given header key
	// By default c.IP() will return the Remote IP from the TCP connection
	// This property can be useful if you are behind a load balancer: X-Forwarded-*
	// NOTE: headers are easily spoofed and the detected IP addresses are unreliable.
	//
	// Default: ""
	ProxyHeader string `json:"proxy_header"`

	// GETOnly rejects all non-GET requests if set to true.
	// This option is useful as anti-DoS protection for servers
	// accepting only GET requests. The request size is limited
	// by ReadBufferSize if GETOnly is set.
	//
	// Default: false
	GETOnly bool `json:"get_only"`

	// ErrorHandler is executed when an error is returned from fiber.Handler.
	//
	// Default: DefaultErrorHandler
	ErrorHandler ErrorHandler `json:"-"`

	// When set to true, disables keep-alive connections.
	// The server will close incoming connections after sending the first response to client.
	//
	// Default: false
	DisableKeepalive bool `json:"disable_keepalive"`

	// When set to true, causes the default date header to be excluded from the response.
	//
	// Default: false
	DisableDefaultDate bool `json:"disable_default_date"`

	// When set to true, causes the default Content-Type header to be excluded from the response.
	//
	// Default: false
	DisableDefaultContentType bool `json:"disable_default_content_type"`

	// When set to true, disables header normalization.
	// By default all header names are normalized: conteNT-tYPE -> Content-Type.
	//
	// Default: false
	DisableHeaderNormalizing bool `json:"disable_header_normalizing"`

	// When set to true, it will not print out the «Fiber» ASCII art and listening address.
	//
	// Default: false
	DisableStartupMessage bool `json:"disable_startup_message"`

	// This function allows to setup app name for the app
	//
	// Default: nil
	AppName string `json:"app_name"`

	// StreamRequestBody enables request body streaming,
	// and calls the handler sooner when given body is
	// larger then the current limit.
	StreamRequestBody bool

	// Will not pre parse Multipart Form data if set to true.
	//
	// This option is useful for servers that desire to treat
	// multipart form data as a binary blob, or choose when to parse the data.
	//
	// Server pre parses multipart form data by default.
	DisablePreParseMultipartForm bool

	// Aggressively reduces memory usage at the cost of higher CPU usage
	// if set to true.
	//
	// Try enabling this option only if the server consumes too much memory
	// serving mostly idle keep-alive connections. This may reduce memory
	// usage by more than 50%.
	//
	// Default: false
	ReduceMemoryUsage bool `json:"reduce_memory_usage"`

	// When set by an external client of Fiber it will use the provided implementation of a
	// JSONMarshal
	//
	// Allowing for flexibility in using another json library for encoding
	// Default: json.Marshal
	JSONEncoder utils.JSONMarshal `json:"-"`

	// Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only)
	// WARNING: When prefork is set to true, only "tcp4" and "tcp6" can be chose.
	//
	// Default: NetworkTCP4
	Network string

	// If you find yourself behind some sort of proxy, like a load balancer,
	// then certain header information may be sent to you using special X-Forwarded-* headers or the Forwarded header.
	// For example, the Host HTTP header is usually used to return the requested host.
	// But when you’re behind a proxy, the actual host may be stored in an X-Forwarded-Host header.
	//
	// If you are behind a proxy, you should enable TrustedProxyCheck to prevent header spoofing.
	// If you enable EnableTrustedProxyCheck and leave TrustedProxies empty Fiber will skip
	// all headers that could be spoofed.
	// If request ip in TrustedProxies whitelist then:
	//   1. c.Protocol() get value from X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl or X-Url-Scheme header
	//   2. c.IP() get value from ProxyHeader header.
	//   3. c.Hostname() get value from X-Forwarded-Host header
	// But if request ip NOT in Trusted Proxies whitelist then:
	//   1. c.Protocol() WON't get value from X-Forwarded-Proto, X-Forwarded-Protocol, X-Forwarded-Ssl or X-Url-Scheme header,
	//    will return https in case when tls connection is handled by the app, of http otherwise
	//   2. c.IP() WON'T get value from ProxyHeader header, will return RemoteIP() from fasthttp context
	//   3. c.Hostname() WON'T get value from X-Forwarded-Host header, fasthttp.Request.URI().Host()
	//    will be used to get the hostname.
	//
	// Default: false
	EnableTrustedProxyCheck bool `json:"enable_trusted_proxy_check"`

	// Read EnableTrustedProxyCheck doc.
	//
	// Default: []string
	TrustedProxies []string `json:"trusted_proxies"`
	// contains filtered or unexported fields
}

Config is a struct holding the server settings.

type ConversionError added in v1.30.1

type ConversionError = schema.ConversionError

Conversion error exposes the internal schema.ConversionError for public use.

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"`
}

Cookie data for c.Cookie

type Ctx

type Ctx struct {
	// contains filtered or unexported fields
}

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

func (*Ctx) Abort added in v1.10.91

func (c *Ctx) Abort(code int, data interface{}) error

func (*Ctx) Accepts

func (c *Ctx) Accepts(offers ...string) string

Accepts checks if the specified extensions or content types are acceptable.

func (*Ctx) AcceptsCharsets

func (c *Ctx) AcceptsCharsets(offers ...string) string

AcceptsCharsets checks if the specified charset is acceptable.

func (*Ctx) AcceptsEncodings

func (c *Ctx) AcceptsEncodings(offers ...string) string

AcceptsEncodings checks if the specified encoding is acceptable.

func (*Ctx) AcceptsLanguages

func (c *Ctx) AcceptsLanguages(offers ...string) string

AcceptsLanguages checks if the specified language is acceptable.

func (*Ctx) App added in v1.20.1

func (c *Ctx) App() *App

App returns the *App reference to the instance of the Fiber application

func (*Ctx) Append

func (c *Ctx) Append(field string, values ...string)

Append the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value.

func (*Ctx) Attachment

func (c *Ctx) Attachment(filename ...string)

Attachment sets the HTTP response Content-Disposition header field to attachment.

func (*Ctx) BaseURL

func (c *Ctx) BaseURL() string

BaseURL returns (protocol + host + base path).

func (*Ctx) Body

func (c *Ctx) Body() []byte

Body contains the raw body submitted in a POST request. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.

func (*Ctx) BodyParser

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

BodyParser binds the request body to a struct. It supports decoding the following content types based on the Content-Type header: application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data If none of the content types above are matched, it will return a ErrUnprocessableEntity error

func (*Ctx) ClearCookie

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

ClearCookie expires a specific cookie by key on the client side. If no key is provided it expires all cookies that came with the request.

func (*Ctx) Contains added in v1.10.91

func (c *Ctx) Contains(key, expect string, args ...string) (has, fit bool)

func (*Ctx) Context added in v1.10.91

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

Context returns *fasthttp.RequestCtx that carries a deadline a cancellation signal, and other values across API boundaries.

func (*Ctx) Cookie

func (c *Ctx) Cookie(cookie *Cookie)

Cookie sets a cookie by passing a cookie struct.

func (*Ctx) CookieStr added in v1.10.91

func (c *Ctx) CookieStr(key string, args ...string) string

func (*Ctx) Cookies

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

Cookies is used for getting a cookie value by key. Defaults to the empty string "" if the cookie doesn't exist. If a default value is given, it will return that value if the cookie doesn't exist. The returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.

func (*Ctx) Deny added in v1.10.91

func (c *Ctx) Deny(msg string) error

func (*Ctx) Download

func (c *Ctx) Download(file string, filename ...string) error

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

func (*Ctx) Errorf added in v1.10.91

func (c *Ctx) Errorf(servCode int, format string, args ...interface{}) error

func (*Ctx) FetchFloat added in v1.10.91

func (c *Ctx) FetchFloat(key string, args ...float64) float64

func (*Ctx) FetchInt added in v1.10.91

func (c *Ctx) FetchInt(key string, args ...int) int

func (*Ctx) FetchStr added in v1.10.91

func (c *Ctx) FetchStr(key string, args ...string) string

Read the POST first, if empty then read GET

func (*Ctx) FormFile

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

FormFile returns the first file by key from a MultipartForm.

func (*Ctx) FormValue

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

FormValue returns the first value by key from a MultipartForm. Defaults to the empty string "" if the form value doesn't exist. If a default value is given, it will return that value if the form value does not exist. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.

func (*Ctx) Format

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

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.

func (*Ctx) Fresh

func (c *Ctx) Fresh() bool

Fresh returns true when the response is still “fresh” in the client's cache, otherwise false is returned to indicate that the client cache is now stale and the full response should be sent. When a client sends the Cache-Control: no-cache request header to indicate an end-to-end reload request, this module will return false to make handling these requests transparent. https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33

func (*Ctx) Get

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

Get returns the HTTP request header specified by field. Field names are case-insensitive Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.

func (*Ctx) GetFloat added in v1.10.91

func (c *Ctx) GetFloat(key string, args ...float64) float64

func (*Ctx) GetInt added in v1.10.91

func (c *Ctx) GetInt(key string, args ...int) int

func (*Ctx) GetStr added in v1.10.91

func (c *Ctx) GetStr(key string, args ...string) string

func (*Ctx) HeaderStr added in v1.10.91

func (c *Ctx) HeaderStr(key string, args ...string) string

func (*Ctx) Hostname

func (c *Ctx) Hostname() string

Hostname contains the hostname derived from the X-Forwarded-Host or Host HTTP header. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead. Please use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.

func (*Ctx) IP

func (c *Ctx) IP() string

IP returns the remote IP address of the request. Please use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.

func (*Ctx) IPs

func (c *Ctx) IPs() (ips []string)

IPs returns an string slice of IP addresses specified in the X-Forwarded-For request header.

func (*Ctx) Is

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

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

func (*Ctx) IsProxyTrusted added in v1.30.1

func (c *Ctx) IsProxyTrusted() bool

func (*Ctx) JSON

func (c *Ctx) JSON(data interface{}) error

JSON converts any interface or string to JSON. Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value. This method also sets the content header to application/json.

func (*Ctx) JSONP

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

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.

func (*Ctx) Jsonify added in v1.10.91

func (c *Ctx) Jsonify(format string, args ...interface{}) error
func (c *Ctx) Links(link ...string)

Links joins the links followed by the property to populate the response's Link HTTP header field.

func (*Ctx) Locals

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

Locals makes it possible to pass interface{} values under string keys scoped to the request and therefore available to all following routes that match the request.

func (*Ctx) Location

func (c *Ctx) Location(path string)

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

func (*Ctx) Method

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

Method contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.

func (*Ctx) MultipartForm

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

MultipartForm parse form entries from binary. This returns a map[string][]string, so given a key the value will be a string slice.

func (*Ctx) Next

func (c *Ctx) Next() (err error)

Next executes the next method in the stack that matches the current route.

func (*Ctx) OriginalURL

func (c *Ctx) OriginalURL() string

OriginalURL contains the original request URL. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.

func (*Ctx) ParamFloat added in v1.10.91

func (c *Ctx) ParamFloat(key string, args ...float64) float64

func (*Ctx) ParamInt added in v1.10.91

func (c *Ctx) ParamInt(key string, args ...int) int

func (*Ctx) ParamStr added in v1.10.91

func (c *Ctx) ParamStr(key string, args ...string) string

func (*Ctx) Params

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

Params is used to get the route parameters. Defaults to empty string "" if the param doesn't exist. If a default value is given, it will return that value if the param doesn't exist. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.

func (*Ctx) ParamsInt added in v1.27.1

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

ParamsInt is used to get an integer from the route parameters it defaults to zero if the parameter is not found or if the parameter cannot be converted to an integer If a default value is given, it will returb that value in case the param doesn't exist or cannot be converted to an integrer

func (*Ctx) Path

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

Path returns the path part of the request URL. Optionally, you could override the path.

func (*Ctx) Port added in v1.30.1

func (c *Ctx) Port() string

Port returns the remote port of the request.

func (*Ctx) PostAll added in v1.10.91

func (c *Ctx) PostAll() (map[string]interface{}, error)

func (*Ctx) PostFloat added in v1.10.91

func (c *Ctx) PostFloat(key string, args ...float64) float64

func (*Ctx) PostInt added in v1.10.91

func (c *Ctx) PostInt(key string, args ...int) int

func (*Ctx) PostStr added in v1.10.91

func (c *Ctx) PostStr(key string, args ...string) string

func (*Ctx) Printf added in v1.10.2

func (c *Ctx) Printf(format string, args ...interface{}) error

Send formatted string

func (*Ctx) Protocol

func (c *Ctx) Protocol() string

Protocol contains the request protocol string: http or https for TLS requests. Use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.

func (*Ctx) Query

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

Query returns the query string parameter in the url. Defaults to empty string "" if the query doesn't exist. If a default value is given, it will return that value if the query doesn't exist. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.

func (*Ctx) QueryParser added in v1.20.1

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

QueryParser binds the query string to a struct.

func (*Ctx) Range

func (c *Ctx) Range(size int) (rangeData Range, err error)

Range returns a struct containing the type and a slice of ranges.

func (*Ctx) Read added in v1.10.2

func (c *Ctx) Read(key, val string, methods ...string) (bool, string)

Common method read data of GET/POST/PARAM/HEADER/COOKIE

func (*Ctx) ReadFloat added in v1.10.91

func (c *Ctx) ReadFloat(key string, val float64, args ...string) (bool, float64)

func (*Ctx) ReadInt added in v1.10.91

func (c *Ctx) ReadInt(key string, val int, args ...string) (bool, int)

func (*Ctx) RealIP added in v1.23.3

func (c *Ctx) RealIP() string

func (*Ctx) Redirect

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

Redirect to the URL derived from the specified path, with specified status. If status is not specified, status defaults to 302 Found.

func (*Ctx) Render

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

Render a template with data and sends a text/html response. We support the following engines: html, amber, handlebars, mustache, pug

func (*Ctx) Reply added in v1.10.91

func (c *Ctx) Reply(data interface{}, metas ...int64) error

func (*Ctx) Request added in v1.20.1

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

Request return the *fasthttp.Request object This allows you to use all fasthttp request methods https://godoc.org/github.com/valyala/fasthttp#Request

func (*Ctx) Response added in v1.20.1

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

Response return the *fasthttp.Response object This allows you to use all fasthttp response methods https://godoc.org/github.com/valyala/fasthttp#Response

func (*Ctx) Route

func (c *Ctx) Route() *Route

Route returns the matched Route struct.

func (*Ctx) SaveFile

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

SaveFile saves any multipart file to disk.

func (*Ctx) Secure

func (c *Ctx) Secure() bool

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

func (*Ctx) Send

func (c *Ctx) Send(body []byte) error

Send sets the HTTP response body without copying it. From this point onward the body argument must not be changed.

func (*Ctx) SendFile

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

SendFile transfers the file from the given path. The file is not compressed by default, enable this by passing a 'true' argument Sets the Content-Type response HTTP header field based on the filenames extension.

func (*Ctx) SendStatus

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

SendStatus sets the HTTP status code and if the response body is empty, it sets the correct status message in the body.

func (*Ctx) SendStream added in v1.20.1

func (c *Ctx) SendStream(stream io.Reader, size ...int) error

SendStream sets response body stream and optional body size.

func (*Ctx) SendString

func (c *Ctx) SendString(body string) error

SendString sets the HTTP response body for string types. This means no type assertion, recommended for faster performance

func (*Ctx) Set

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

Set sets the response's HTTP header field to the specified key, value.

func (*Ctx) SetStatus added in v1.10.3

func (c *Ctx) SetStatus(status int) *Ctx

Status sets the HTTP status for the response.

func (*Ctx) SetType added in v1.10.3

func (c *Ctx) SetType(extension string, charset ...string) *Ctx

Type sets the Content-Type HTTP header to the MIME type specified by the file extension.

func (*Ctx) SetUserContext added in v1.30.1

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

SetUserContext sets a context implementation by user.

func (*Ctx) Stale

func (c *Ctx) Stale() bool

Stale is not implemented yet, pull requests are welcome!

func (*Ctx) Status

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

Status sets the HTTP status for the response. This method is chainable.

func (*Ctx) String added in v1.20.1

func (c *Ctx) String() string

String returns unique string representation of the ctx.

The returned value may be useful for logging.

func (*Ctx) Subdomains

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

Subdomains returns a string slice of subdomains in the domain name of the request. The subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.

func (*Ctx) Token added in v1.10.91

func (c *Ctx) Token() (token string)

func (*Ctx) Type

func (c *Ctx) Type(extension string, charset ...string) *Ctx

Type sets the Content-Type HTTP header to the MIME type specified by the file extension.

func (*Ctx) UserContext added in v1.30.1

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

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

func (*Ctx) Vary

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

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.

func (*Ctx) Write

func (c *Ctx) Write(p []byte) (int, error)

Write appends p into response body.

func (*Ctx) WriteString added in v1.20.3

func (c *Ctx) WriteString(s string) (int, error)

WriteString appends s to response body.

func (*Ctx) XHR

func (c *Ctx) XHR() bool

XHR returns 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).

type EmptyFieldError added in v1.30.1

type EmptyFieldError = schema.EmptyFieldError

EmptyFieldError error exposes the internal schema.EmptyFieldError for public use.

type Error added in v1.20.1

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

Error represents an error that occurred while handling a request.

func NewError added in v1.20.1

func NewError(code int, message ...string) *Error

NewError creates a new Error instance with an optional message

func (*Error) Error added in v1.20.1

func (e *Error) Error() string

Error makes it compatible with the `error` interface.

type ErrorHandler added in v1.20.1

type ErrorHandler = func(*Ctx, error) error

ErrorHandler defines a function that will process all errors returned from any handlers in the stack

cfg := fiber.Config{}
cfg.ErrorHandler = func(c *Ctx, err error) error {
 code := StatusInternalServerError
 if e, ok := err.(*Error); ok {
   code = e.Code
 }
 c.Set(HeaderContentType, MIMETextPlainCharsetUTF8)
 return c.Status(code).SendString(err.Error())
}
app := fiber.New(cfg)

type FormFile added in v1.26.0

type FormFile struct {
	// Fieldname is form file's field name
	Fieldname string
	// Name is form file's name
	Name string
	// Content is form file's content
	Content []byte
	// contains filtered or unexported fields
}

FormFile represents multipart form file

func AcquireFormFile added in v1.26.0

func AcquireFormFile() *FormFile

AcquireFormFile returns an empty FormFile object from the pool.

The returned FormFile may be returned to the pool with ReleaseFormFile when no longer needed. This allows reducing GC load.

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group struct

func (*Group) Add

func (grp *Group) Add(method, path string, handlers ...Handler) Router

Add allows you to specify a HTTP method to register a route

func (*Group) All

func (grp *Group) All(path string, handlers ...Handler) Router

All will register the handler on all HTTP methods

func (*Group) Connect

func (grp *Group) Connect(path string, handlers ...Handler) Router

Connect registers a route for CONNECT methods that establishes a tunnel to the server identified by the target resource.

func (*Group) Delete

func (grp *Group) Delete(path string, handlers ...Handler) Router

Delete registers a route for DELETE methods that deletes the specified resource.

func (*Group) Get

func (grp *Group) Get(path string, handlers ...Handler) Router

Get registers a route for GET methods that requests a representation of the specified resource. Requests using GET should only retrieve data.

func (*Group) Group

func (grp *Group) Group(prefix string, handlers ...Handler) Router

Group is used for Routes with common prefix to define a new sub-router with optional middleware.

api := app.Group("/api")
api.Get("/users", handler)

func (*Group) Head

func (grp *Group) Head(path string, handlers ...Handler) Router

Head registers a route for HEAD methods that asks for a response identical to that of a GET request, but without the response body.

func (*Group) Mount added in v1.10.1

func (grp *Group) Mount(prefix string, fiber *App) Router

Mount attaches another app instance as a sub-router along a routing path. It's very useful to split up a large API as many independent routers and compose them as a single service using Mount.

func (*Group) Options

func (grp *Group) Options(path string, handlers ...Handler) Router

Options registers a route for OPTIONS methods that is used to describe the communication options for the target resource.

func (*Group) Patch

func (grp *Group) Patch(path string, handlers ...Handler) Router

Patch registers a route for PATCH methods that is used to apply partial modifications to a resource.

func (*Group) Post

func (grp *Group) Post(path string, handlers ...Handler) Router

Post registers a route for POST methods that is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

func (*Group) Put

func (grp *Group) Put(path string, handlers ...Handler) Router

Put registers a route for PUT methods that replaces all current representations of the target resource with the request payload.

func (*Group) Static

func (grp *Group) Static(prefix, root string, config ...Static) Router

Static will create a file server serving static files

func (*Group) Trace

func (grp *Group) Trace(path string, handlers ...Handler) Router

Trace registers a route for TRACE methods that performs a message loop-back test along the path to the target resource.

func (*Group) Use

func (grp *Group) Use(args ...interface{}) Router

Use registers a middleware route that will match requests with the provided prefix (which is optional and defaults to "/").

app.Use(func(c *fiber.Ctx) error {
     return c.Next()
})
app.Use("/api", func(c *fiber.Ctx) error {
     return c.Next()
})
app.Use("/api", handler, func(c *fiber.Ctx) error {
     return c.Next()
})

This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...

type Handler added in v1.10.5

type Handler = func(*Ctx) error

Handler defines a function to serve HTTP requests.

type Map

type Map map[string]interface{}

Map is a shortcut for map[string]interface{}, useful for JSON returns

type MultiError added in v1.30.1

type MultiError = schema.MultiError

MultiError error exposes the internal schema.MultiError for public use.

type Range

type Range struct {
	Type   string
	Ranges []struct {
		Start int
		End   int
	}
}

Range data for c.Range

type ReplyBody added in v1.10.91

type ReplyBody Map

Give the difference of reponse body or reponse data

type Request added in v1.26.0

type Request = fasthttp.Request

Request represents HTTP request.

It is forbidden copying Request instances. Create new instances and use CopyTo instead.

Request instance MUST NOT be used from concurrently running goroutines. Copy from fasthttp

type Response added in v1.26.0

type Response = fasthttp.Response

Response represents HTTP response.

It is forbidden copying Response instances. Create new instances and use CopyTo instead.

Response instance MUST NOT be used from concurrently running goroutines. Copy from fasthttp

func AcquireResponse added in v1.26.0

func AcquireResponse() *Response

AcquireResponse returns an empty Response instance from response pool.

The returned Response instance may be passed to ReleaseResponse when it is no longer needed. This allows Response recycling, reduces GC pressure and usually improves performance. Copy from fasthttp

type Route added in v1.10.91

type Route struct {

	// Public fields
	Method   string    `json:"method"` // HTTP method
	Path     string    `json:"path"`   // Original registered route path
	Params   []string  `json:"params"` // Case sensitive param keys
	Handlers []Handler `json:"-"`      // Ctx handlers
	// contains filtered or unexported fields
}

Route is a struct that holds all metadata for each registered handler

type Router added in v1.20.1

type Router interface {
	Use(args ...interface{}) Router

	Get(path string, handlers ...Handler) Router
	Head(path string, handlers ...Handler) Router
	Post(path string, handlers ...Handler) Router
	Put(path string, handlers ...Handler) Router
	Delete(path string, handlers ...Handler) Router
	Connect(path string, handlers ...Handler) Router
	Options(path string, handlers ...Handler) Router
	Trace(path string, handlers ...Handler) Router
	Patch(path string, handlers ...Handler) Router

	Add(method, path string, handlers ...Handler) Router
	Static(prefix, root string, config ...Static) Router
	All(path string, handlers ...Handler) Router

	Group(prefix string, handlers ...Handler) Router

	Mount(prefix string, fiber *App) Router
}

Router defines all router handle interface includes app and group router.

type Static

type Static struct {
	// When set to true, the server tries minimizing CPU usage by caching compressed files.
	// This works differently than the github.com/gofiber/compression middleware.
	// Optional. Default value false
	Compress bool `json:"compress"`

	// When set to true, enables byte range requests.
	// Optional. Default value false
	ByteRange bool `json:"byte_range"`

	// When set to true, enables directory browsing.
	// Optional. Default value false.
	Browse bool `json:"browse"`

	// The name of the index file for serving a directory.
	// Optional. Default value "index.html".
	Index string `json:"index"`

	// Expiration duration for inactive file handlers.
	// Use a negative time.Duration to disable it.
	//
	// Optional. Default value 10 * time.Second.
	CacheDuration time.Duration `json:"cache_duration"`

	// The value for the Cache-Control HTTP-header
	// that is set on the file response. MaxAge is defined in seconds.
	//
	// Optional. Default value 0.
	MaxAge int `json:"max_age"`

	// Next defines a function to skip this middleware when returned true.
	//
	// Optional. Default: nil
	Next func(c *Ctx) bool
}

Static defines configuration options when defining static assets.

type Storage added in v1.21.2

type Storage interface {
	// Get gets the value for the given key.
	// It returns ErrNotFound if the storage does not contain the key.
	Get(key string) ([]byte, error)

	// Set stores the given value for the given key along with a
	// time-to-live expiration value, 0 means live for ever
	// Empty key or value will be ignored without an error.
	Set(key string, val []byte, ttl time.Duration) error

	// Delete deletes the value for the given key.
	// It returns no error if the storage does not contain the key,
	Delete(key string) error

	// Reset resets the storage and delete all keys.
	Reset() error

	// Close closes the storage and will stop any running garbage
	// collectors and open connections.
	Close() error
}

Storage interface for communicating with different database/key-value providers

type UnknownKeyError added in v1.30.1

type UnknownKeyError = schema.UnknownKeyError

UnknownKeyError error exposes the internal schema.UnknownKeyError for public use.

type Views added in v1.20.1

type Views interface {
	Load() error
	Render(io.Writer, string, interface{}, ...string) error
}

Views is the interface that wraps the Render function.

Directories

Path Synopsis
internal
fasttemplate
Package fasttemplate implements simple and fast template library.
Package fasttemplate implements simple and fast template library.
fwd
The `fwd` package provides a buffered reader and writer.
The `fwd` package provides a buffered reader and writer.
msgp
This package is the support library for the msgp code generator (http://github.com/tinylib/msgp).
This package is the support library for the msgp code generator (http://github.com/tinylib/msgp).
schema
Package gorilla/schema fills a struct with form values.
Package gorilla/schema fills a struct with form values.
uuid
Package uuid generates and inspects UUIDs.
Package uuid generates and inspects UUIDs.
wmi
Package wmi provides a WQL interface for WMI on Windows.
Package wmi provides a WQL interface for WMI on Windows.
middleware
cache
Special thanks to @codemicro for moving this to fiber core Original middleware: github.com/codemicro/fiber-cache
Special thanks to @codemicro for moving this to fiber core Original middleware: github.com/codemicro/fiber-cache

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL