// Serve files from multiple directories
app.Static("/","./public")// Serve files from "./files" directory:
app.Static("/","./files")
You can use any virtual path prefix (where the path does not actually exist in the file system) for files that are served by the Static method, specify a prefix path for the static directory, as shown below:
If you want to have a little bit more control regarding the settings for serving static files. You could use the fiber.Static struct to enable specific settings.
// Static defines configuration options when defining static assets.
typeStaticstruct{// 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
Compressbool`json:"compress"`// When set to true, enables byte range requests.
// Optional. Default value false
ByteRangebool`json:"byte_range"`// When set to true, enables directory browsing.
// Optional. Default value false.
Browsebool`json:"browse"`// When set to true, enables direct download.
// Optional. Default value false.
Downloadbool`json:"download"`// The name of the index file for serving a directory.
// Optional. Default value "index.html".
Indexstring`json:"index"`// Expiration duration for inactive file handlers.
// Use a negative time.Duration to disable it.
//
// Optional. Default value 10 * time.Second.
CacheDurationtime.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.
MaxAgeint`json:"max_age"`// ModifyResponse defines a function that allows you to alter the response.
//
// Optional. Default: nil
ModifyResponseHandler// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Nextfunc(c*Ctx)bool}
Registers a route bound to a specific HTTP method.
注册绑定到特定 HTTP 方法的路由。
Signatures
签名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// HTTP methods
func(app*App)Get(pathstring,handlers...Handler)Routerfunc(app*App)Head(pathstring,handlers...Handler)Routerfunc(app*App)Post(pathstring,handlers...Handler)Routerfunc(app*App)Put(pathstring,handlers...Handler)Routerfunc(app*App)Delete(pathstring,handlers...Handler)Routerfunc(app*App)Connect(pathstring,handlers...Handler)Routerfunc(app*App)Options(pathstring,handlers...Handler)Routerfunc(app*App)Trace(pathstring,handlers...Handler)Routerfunc(app*App)Patch(pathstring,handlers...Handler)Router// Add allows you to specifiy a method as value
func(app*App)Add(method,pathstring,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(pathstring,handlers...Handler)Router
Examples
示例
1
2
3
4
5
6
7
8
9
// Simple GET handler
app.Get("/api/list",func(c*fiber.Ctx)error{returnc.SendString("I'm a GET request!")})// Simple POST handler
app.Post("/api/register",func(c*fiber.Ctx)error{returnc.SendString("I'm a POST request!")})
Use can be used for middleware packages and prefix catchers. These routes will only match the beginning of each path i.e. /john will match /john/doe, /johnnnnn etc
Use 可用于中间件包和前缀捕获器。这些路由将仅匹配每个路径的开头,即 /john 将匹配 /john/doe 、 /johnnnnn 等
// Match any request
app.Use(func(c*fiber.Ctx)error{returnc.Next()})// Match request starting with /api
app.Use("/api",func(c*fiber.Ctx)error{returnc.Next()})// Match requests starting with /api or /home (multiple-prefix support)
app.Use([]string{"/api","/home"},func(c*fiber.Ctx)error{returnc.Next()})// Attach multiple handlers
app.Use("/api",func(c*fiber.Ctx)error{c.Set("X-Custom-Header",random.String(32))returnc.Next()},func(c*fiber.Ctx)error{returnc.Next()})
Mount 挂载
You can Mount Fiber instance by creating a *Mount
您可以通过创建 *Mount 来挂载 Fiber 实例
Signature
签名
1
func(a*App)Mount(prefixstring,app*App)Router
Examples
示例
1
2
3
4
5
6
7
8
9
10
11
funcmain(){app:=fiber.New()micro:=fiber.New()app.Mount("/john",micro)// GET /john/doe -> 200 OK
micro.Get("/doe",func(c*fiber.Ctx)error{returnc.SendStatus(fiber.StatusOK)})log.Fatal(app.Listen(":3000"))}
MountPath
The MountPath property contains one or more path patterns on which a sub-app was mounted.
Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners and then waits indefinitely for all connections to return to idle before shutting down.
ListenMutualTLSWithCertificate serves HTTPs requests from the given address using certFile, keyFile and clientCertFile are the paths to TLS certificate and key file
Testing your application is done with the Test method. Use this method for creating _test.go files or when you need to debug your routing logic. The default timeout is 1s if you want to disable a timeout altogether, pass -1 as a second argument.
使用 Test 方法测试您的应用程序。使用此方法创建 _test.go 文件或当您需要调试路由逻辑时。默认超时为 1s ,如果您想完全禁用超时,请将 -1 作为第二个参数传递。
// 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
returnc.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:
ifresp.StatusCode==fiber.StatusOK{body,_:=io.ReadAll(resp.Body)fmt.Println(string(body))// => Hello, World!
}