🚀 应用
静态
使用 静态 方法来提供静态文件,例如 图片、CSS, 和 JavaScript。
默认情况下,静态 将提供 index.html
文件,以响应目录请求。
func (app *App) Static(prefix, root string, config ...Static) Router
使用以下代码来提供位于命名为 ./public
的目录中的文件
app.Static("/", "./public")
// => http://localhost:3000/hello.html
// => http://localhost:3000/js/jquery.js
// => http://localhost:3000/css/style.css
// Serve files from multiple directories
app.Static("/", "./public")
// Serve files from "./files" directory:
app.Static("/", "./files")
您可以使用任何虚拟路径前缀 (该路径实际不存在于文件系统中) 用于通过 静态 方法提供的文件,为静态目录指定一个前缀路径,如下所示
app.Static("/static", "./public")
// => http://localhost:3000/static/hello.html
// => http://localhost:3000/static/js/jquery.js
// => http://localhost:3000/static/css/style.css
如果您想对提供静态文件的设置有更多控制,可以使用 fiber.Static
结构体来启用特定设置。
// Static defines configuration options when defining static assets.
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"`
// When set to true, enables direct download.
// Optional. Default value false.
Download bool `json:"download"`
// 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"`
// ModifyResponse defines a function that allows you to alter the response.
//
// Optional. Default: nil
ModifyResponse Handler
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *Ctx) bool
}
// Custom config
app.Static("/", "./public", fiber.Static{
Compress: true,
ByteRange: true,
Browse: true,
Index: "john.html",
CacheDuration: 10 * time.Second,
MaxAge: 3600,
})
路由处理器
注册绑定到特定 HTTP 方法 的路由。
// HTTP methods
func (app *App) Get(path string, handlers ...Handler) Router
func (app *App) Head(path string, handlers ...Handler) Router
func (app *App) Post(path string, handlers ...Handler) Router
func (app *App) Put(path string, handlers ...Handler) Router
func (app *App) Delete(path string, handlers ...Handler) Router
func (app *App) Connect(path string, handlers ...Handler) Router
func (app *App) Options(path string, handlers ...Handler) Router
func (app *App) Trace(path string, handlers ...Handler) Router
func (app *App) Patch(path string, handlers ...Handler) Router
// Add allows you to specifiy a method as value
func (app *App) Add(method, path string, handlers ...Handler) Router
// All will register the route on all HTTP methods
// Almost the same as app.Use but not bound to prefixes
func (app *App) All(path string, handlers ...Handler) Router
// Simple GET handler
app.Get("/api/list", func(c *fiber.Ctx) error {
return c.SendString("I'm a GET request!")
})
// Simple POST handler
app.Post("/api/register", func(c *fiber.Ctx) error {
return c.SendString("I'm a POST request!")
})
Use 可用于中间件包和前缀捕获器。这些路由只匹配每个路径的开头,即 /john
将匹配 /john/doe
、/johnnnnn
等
func (app *App) Use(args ...interface{}) Router
// Match any request
app.Use(func(c *fiber.Ctx) error {
return c.Next()
})
// Match request starting with /api
app.Use("/api", func(c *fiber.Ctx) error {
return c.Next()
})
// Match requests starting with /api or /home (multiple-prefix support)
app.Use([]string{"/api", "/home"}, func(c *fiber.Ctx) error {
return c.Next()
})
// Attach multiple handlers
app.Use("/api", func(c *fiber.Ctx) error {
c.Set("X-Custom-Header", random.String(32))
return c.Next()
}, func(c *fiber.Ctx) error {
return c.Next()
})
挂载
您可以挂载 Fiber 实例,通过创建一个 *Mount
func (a *App) Mount(prefix string, app *App) Router
func main() {
app := fiber.New()
micro := fiber.New()
app.Mount("/john", micro) // GET /john/doe -> 200 OK
micro.Get("/doe", func(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusOK)
})
log.Fatal(app.Listen(":3000"))
}
挂载路径
MountPath
属性包含一个或多个在其上挂载了子应用的路径模式。
func (app *App) MountPath() string
func main() {
app := fiber.New()
one := fiber.New()
two := fiber.New()
three := fiber.New()
two.Mount("/three", three)
one.Mount("/two", two)
app.Mount("/one", one)
one.MountPath() // "/one"
two.MountPath() // "/one/two"
three.MountPath() // "/one/two/three"
app.MountPath() // ""
}
挂载顺序对于 MountPath 很重要。如果您想正确获取挂载路径,应该从最深层的应用开始挂载。
分组
您可以对路由进行分组,通过创建一个 *Group
结构体。
func (app *App) Group(prefix string, handlers ...Handler) Router
func main() {
app := fiber.New()
api := app.Group("/api", handler) // /api
v1 := api.Group("/v1", handler) // /api/v1
v1.Get("/list", handler) // /api/v1/list
v1.Get("/user", handler) // /api/v1/user
v2 := api.Group("/v2", handler) // /api/v2
v2.Get("/list", handler) // /api/v2/list
v2.Get("/user", handler) // /api/v2/user
log.Fatal(app.Listen(":3000"))
}
路由
您可以在公共函数内定义带有公共前缀的路由。
func (app *App) Route(prefix string, fn func(router Router), name ...string) Router
func main() {
app := fiber.New()
app.Route("/test", func(api fiber.Router) {
api.Get("/foo", handler).Name("foo") // /test/foo (name: test.foo)
api.Get("/bar", handler).Name("bar") // /test/bar (name: test.bar)
}, "test.")
log.Fatal(app.Listen(":3000"))
}
服务器
Server 返回底层的 fasthttp 服务器
func (app *App) Server() *fasthttp.Server
func main() {
app := fiber.New()
app.Server().MaxConnsPerIP = 1
// ...
}
服务器关闭
Shutdown 方法优雅地关闭服务器,而不会中断任何活动连接。Shutdown 的工作原理是首先关闭所有打开的监听器,然后无限期地等待所有连接返回空闲状态,然后再关闭。
ShutdownWithTimeout 将在超时时间到期后强制关闭任何活动连接。
ShutdownWithContext 关闭服务器,如果在上下文的截止日期超过时,包括强制关闭。
func (app *App) Shutdown() error
func (app *App) ShutdownWithTimeout(timeout time.Duration) error
func (app *App) ShutdownWithContext(ctx context.Context) error
处理器数量
此方法返回注册的处理器数量。
func (app *App) HandlersCount() uint32
堆栈
此方法返回原始的路由堆栈
func (app *App) Stack() [][]*Route
var handler = func(c *fiber.Ctx) error { return nil }
func main() {
app := fiber.New()
app.Get("/john/:age", handler)
app.Post("/register", handler)
data, _ := json.MarshalIndent(app.Stack(), "", " ")
fmt.Println(string(data))
app.Listen(":3000")
}
[
[
{
"method": "GET",
"path": "/john/:age",
"params": [
"age"
]
}
],
[
{
"method": "HEAD",
"path": "/john/:age",
"params": [
"age"
]
}
],
[
{
"method": "POST",
"path": "/register",
"params": null
}
]
]
名称
此方法指定最新创建的路由的名称。
func (app *App) Name(name string) Router
var handler = func(c *fiber.Ctx) error { return nil }
func main() {
app := fiber.New()
app.Get("/", handler)
app.Name("index")
app.Get("/doe", handler).Name("home")
app.Trace("/tracer", handler).Name("tracert")
app.Delete("/delete", handler).Name("delete")
a := app.Group("/a")
a.Name("fd.")
a.Get("/test", handler).Name("test")
data, _ := json.MarshalIndent(app.Stack(), "", " ")
fmt.Print(string(data))
app.Listen(":3000")
}
[
[
{
"method": "GET",
"name": "index",
"path": "/",
"params": null
},
{
"method": "GET",
"name": "home",
"path": "/doe",
"params": null
},
{
"method": "GET",
"name": "fd.test",
"path": "/a/test",
"params": null
}
],
[
{
"method": "HEAD",
"name": "",
"path": "/",
"params": null
},
{
"method": "HEAD",
"name": "",
"path": "/doe",
"params": null
},
{
"method": "HEAD",
"name": "",
"path": "/a/test",
"params": null
}
],
null,
null,
[
{
"method": "DELETE",
"name": "delete",
"path": "/delete",
"params": null
}
],
null,
null,
[
{
"method": "TRACE",
"name": "tracert",
"path": "/tracer",
"params": null
}
],
null
]
GetRoute
此方法根据名称获取路由。
func (app *App) GetRoute(name string) Route
var handler = func(c *fiber.Ctx) error { return nil }
func main() {
app := fiber.New()
app.Get("/", handler).Name("index")
data, _ := json.MarshalIndent(app.GetRoute("index"), "", " ")
fmt.Print(string(data))
app.Listen(":3000")
}
{
"method": "GET",
"name": "index",
"path": "/",
"params": null
}
GetRoutes
此方法获取所有路由。
func (app *App) GetRoutes(filterUseOption ...bool) []Route
当 filterUseOption
等于 true 时,它将过滤由中间件注册的路由。
func main() {
app := fiber.New()
app.Post("/", func (c *fiber.Ctx) error {
return c.SendString("Hello, World!")
}).Name("index")
data, _ := json.MarshalIndent(app.GetRoutes(true), "", " ")
fmt.Print(string(data))
}
[
{
"method": "POST",
"name": "index",
"path": "/",
"params": null
}
]
配置
Config 返回应用程序配置作为值 (只读)。
func (app *App) Config() Config
Handler
Handler 返回可用于处理自定义 *fasthttp.RequestCtx
请求的服务器处理器。
func (app *App) Handler() fasthttp.RequestHandler
监听
Listen 方法处理来自给定地址的 HTTP 请求。
func (app *App) Listen(addr string) error
// Listen on port :8080
app.Listen(":8080")
// Custom host
app.Listen("127.0.0.1:8080")
ListenTLS
ListenTLS 处理来自给定地址的 HTTPS 请求,使用 certFile
和 keyFile
路径作为 TLS 证书文件和密钥文件。
func (app *App) ListenTLS(addr, certFile, keyFile string) error
app.ListenTLS(":443", "./cert.pem", "./cert.key");
使用 ListenTLS
默认采用以下配置 ( 使用 Listener
提供您自己的配置 )
&tls.Config{
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{
cert,
},
}
ListenTLSWithCertificate
func (app *App) ListenTLS(addr string, cert tls.Certificate) error
app.ListenTLSWithCertificate(":443", cert);
使用 ListenTLSWithCertificate
默认采用以下配置 ( 使用 Listener
提供您自己的配置 )
&tls.Config{
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{
cert,
},
}
ListenMutualTLS
ListenMutualTLS 处理来自给定地址的 HTTPS 请求,使用 certFile
、keyFile
和 clientCertFile
作为 TLS 证书文件和密钥文件的路径
func (app *App) ListenMutualTLS(addr, certFile, keyFile, clientCertFile string) error
app.ListenMutualTLS(":443", "./cert.pem", "./cert.key", "./ca-chain-cert.pem");
使用 ListenMutualTLS
默认采用以下配置 ( 使用 Listener
提供您自己的配置 )
&tls.Config{
MinVersion: tls.VersionTLS12,
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: clientCertPool,
Certificates: []tls.Certificate{
cert,
},
}
ListenMutualTLSWithCertificate
ListenMutualTLSWithCertificate 处理来自给定地址的 HTTPS 请求,使用 certFile
、keyFile
和 clientCertFile
作为 TLS 证书文件和密钥文件的路径
func (app *App) ListenMutualTLSWithCertificate(addr string, cert tls.Certificate, clientCertPool *x509.CertPool) error
app.ListenMutualTLSWithCertificate(":443", cert, clientCertPool);
使用 ListenMutualTLSWithCertificate
默认采用以下配置 ( 使用 Listener
提供您自己的配置 )
&tls.Config{
MinVersion: tls.VersionTLS12,
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: clientCertPool,
Certificates: []tls.Certificate{
cert,
},
}
Listener
您可以传递您自己的 net.Listener
,使用 Listener
方法。此方法可用于启用 TLS/HTTPS,使用自定义的 tls.Config
。
func (app *App) Listener(ln net.Listener) error
ln, _ := net.Listen("tcp", ":3000")
cer, _:= tls.LoadX509KeyPair("server.crt", "server.key")
ln = tls.NewListener(ln, &tls.Config{Certificates: []tls.Certificate{cer}})
app.Listener(ln)
测试
可以使用 Test 方法来测试您的应用程序。使用此方法创建 _test.go
文件或在需要调试路由逻辑时使用。默认超时时间为 1s
,如果您想完全禁用超时,传递 -1
作为第二个参数。
func (app *App) Test(req *http.Request, msTimeout ...int) (*http.Response, error)
// Create route with GET method for test:
app.Get("/", func(c *fiber.Ctx) error {
fmt.Println(c.BaseURL()) // => http://google.com
fmt.Println(c.Get("X-Custom-Header")) // => hi
return c.SendString("hello, World!")
})
// http.Request
req := httptest.NewRequest("GET", "http://google.com", nil)
req.Header.Set("X-Custom-Header", "hi")
// http.Response
resp, _ := app.Test(req)
// Do something with results:
if resp.StatusCode == fiber.StatusOK {
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body)) // => Hello, World!
}
钩子
Hooks 是一个方法,返回 钩子 属性。
func (app *App) Hooks() *Hooks