文件服务
FileSystem
用于 Fiber 的文件系统中间件,使你能够从一个目录中提供文件。
⚠️ :params
& :optionals?
在前缀路径中不支持!。
目录
签名
func New(config Config) fiber.Handler
示例
导入作为 Fiber 网络框架一部分的中间件包
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
)
在你启动你的Fiber应用程序后,你可以使用以下可能性。
//提供一个最小的配置
app.Use(filesystem.New(filesystem.Config{)
Root:http.Dir("./assets")
}))
// 或者扩展你的配置以实现定制化
app.Use(filesystem.New(filesystem.Config{
Root: http.Dir("./assets"),
Browse: true,
Index: "index.html",
NotFoundFile: "404.html",
MaxAge: 3600,
}))
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
packge 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
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
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
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
"<Your go module>/statik"
fs "github.com/rakyll/statik/fs"
)
func main() {
statik, err := fs.New()
if err != nil {
panic(err)
}
app := fiber.New()
app.Use("/", filesystem.New(filesystem.Config{
Root: statikFS,
})
log.Fatal(app.Listen(":3000"))
}
配置
// Config定义了中间件的配置。
type Config struct {
// 下一步定义了一个函数,当返回真时跳过这个中间件。
//
// 可选。默认值:nil
Next func(c *fiber.Ctx) bool
// 根是一个文件系统,可以访问
// 到一个文件和目录的集合。
//
// 需要。默认值:nil
Root http.FileSystem `json:"-"`
// 启用目录浏览功能。
//
// 可选。默认值: false
Browse bool `json: "browse"`
// 为目录提供服务的索引文件。
//
// 可选。默认为:"index.html"
Index string `json: "index"`
// 缓存控制(Cache-Control)HTTP头的值。
// 的值,它被设置在文件响应上。MaxAge的单位是秒。
//
// 可选的。默认值为0。
MaxAge int `json: "max_age"`.
// 如果没有找到路径,要返回的文件。对SPA很有用。
//
// 可选。默认值: ""
NotFoundFile string `json: "not_found_file"`。
}
默认配置
var ConfigDefault = Config{
Next: nil,
Root: nil,
Browse: false,
Index: "/index.html",
MaxAge: 0,
}
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。