跳到主要内容
版本: v2.x

文件系统

用于 Fiber 的文件系统中间件,可让你从目录中提供文件。

注意

前缀路径中的 :params & :optionals? 不支持!

为了处理包含空格(或其他 URL 编码值)的路径,请确保设置 fiber.Config{ UnescapePath: true }

函数签名

func New(config Config) fiber.Handler

示例

导入 Fiber Web 框架中包含的中间件包

import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
)

初始化 Fiber 应用后,可以使用以下几种方式

// Provide a minimal config
app.Use(filesystem.New(filesystem.Config{
Root: http.Dir("./assets"),
}))

// Or extend your config for customization
app.Use(filesystem.New(filesystem.Config{
Root: http.Dir("./assets"),
Browse: true,
Index: "index.html",
NotFoundFile: "404.html",
MaxAge: 3600,
}))

如果你的环境(Go 1.16+)支持,我们建议使用 Go Embed 而不是列出的其他方案,因为它原生地集成在 Go 中,而且是最易于使用的。

嵌入

Embed 是将文件嵌入 Go 可执行文件的原生方法。在 Go 1.16 中引入。

package main

import (
"embed"
"io/fs"
"log"
"net/http"

"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
)

// Embed a single file
//go:embed index.html
var f embed.FS

// Embed a directory
//go:embed static/*
var embedDirStatic embed.FS

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

app.Use("/", filesystem.New(filesystem.Config{
Root: http.FS(f),
}))

// Access file "image.png" under `static/` directory via URL: `http://<server>/static/image.png`.
// Without `PathPrefix`, you have to access it via URL:
// `http://<server>/static/static/image.png`.
app.Use("/static", filesystem.New(filesystem.Config{
Root: http.FS(embedDirStatic),
PathPrefix: "static",
Browse: true,
}))

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

pkger

https://github.com/markbates/pkger

package main

import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"

"github.com/markbates/pkger"
)

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

app.Use("/assets", filesystem.New(filesystem.Config{
Root: pkger.Dir("/assets"),
}))

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

packr

https://github.com/gobuffalo/packr

package main

import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"

"github.com/gobuffalo/packr/v2"
)

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

app.Use("/assets", filesystem.New(filesystem.Config{
Root: packr.New("Assets Box", "/assets"),
}))

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

go.rice

https://github.com/GeertJohan/go.rice

package main

import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"

"github.com/GeertJohan/go.rice"
)

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

app.Use("/assets", filesystem.New(filesystem.Config{
Root: rice.MustFindBox("assets").HTTPBox(),
}))

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

fileb0x

https://github.com/UnnoTed/fileb0x

package main

import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"

"<Your go module>/myEmbeddedFiles"
)

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

app.Use("/assets", filesystem.New(filesystem.Config{
Root: myEmbeddedFiles.HTTP,
}))

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

statik

https://github.com/rakyll/statik

package main

import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"

// Use blank to invoke init function and register data to statik
_ "<Your go module>/statik"
"github.com/rakyll/statik/fs"
)

func main() {
statikFS, err := fs.New()
if err != nil {
panic(err)
}

app := fiber.New()

app.Use("/", filesystem.New(filesystem.Config{
Root: statikFS,
}))

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

配置

属性类型描述默认值
下一页func(*fiber.Ctx) boolNext 定义一个函数,当返回 true 时跳过此中间件。nil
根目录http.FileSystemRoot 是一个提供文件和目录集合访问权限的 FileSystem。nil
路径前缀stringPathPrefix 定义一个前缀,在从 FileSystem 读取文件时添加到文件路径中。""
浏览bool启用目录浏览。false
索引string用于服务目录的索引文件。"index.html"
最大缓存时间int设置在文件响应上的 Cache-Control HTTP 头的数值。MaxAge 以秒为单位定义。0
未找到文件string如果路径未找到时返回的文件。对 SPA(单页应用)很有用。""
内容类型字符集string设置在文件响应上的 Content-Type HTTP 头的数值。""

默认配置

var ConfigDefault = Config{
Next: nil,
Root: nil,
PathPrefix: "",
Browse: false,
Index: "/index.html",
MaxAge: 0,
ContentTypeCharset: "",
}

工具函数

发送文件

从指定的 HTTP 文件系统路径提供文件服务。

函数签名
func SendFile(c *fiber.Ctx, filesystem http.FileSystem, path string) error

导入 Fiber Web 框架中包含的中间件包

import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
)
示例
// Define a route to serve a specific file
app.Get("/download", func(c *fiber.Ctx) error {
// Serve the file using SendFile function
err := filesystem.SendFile(c, http.Dir("your/filesystem/root"), "path/to/your/file.txt")
if err != nil {
// Handle the error, e.g., return a 404 Not Found response
return c.Status(fiber.StatusNotFound).SendString("File not found")
}

return nil
})
示例
// Serve static files from the "build" directory using Fiber's built-in middleware.
app.Use("/", filesystem.New(filesystem.Config{
Root: http.FS(f), // Specify the root directory for static files.
PathPrefix: "build", // Define the path prefix where static files are served.
}))

// For all other routes (wildcard "*"), serve the "index.html" file from the "build" directory.
app.Use("*", func(ctx *fiber.Ctx) error {
return filesystem.SendFile(ctx, http.FS(f), "build/index.html")
})