// 최소한의 설정 제공
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,
}))
환경(Go 1.16+)이 지원하는 경우 나열된 다른 솔루션 대신 Go Embed를 사용하는 것이 좋습니다. 이는 Go에 기본 제공되며 사용이 가장 쉽습니다.
embed
package main
import (
"embed"
"io/fs"
"log"
"net/http"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
)
// 단일 파일 포함
//go:embed index.html
var f embed.FS
// 디렉토리 포함
//go:embed static/*
var embedDirStatic embed.FS
func main() {
app := fiber.New()
app.Use("/", filesystem.New(filesystem.Config{
Root: http.FS(f),
}))
// `static/` 디렉토리 아래의 "image.png" 파일에 URL을 통해 액세스: `http://<server>/static/image.png`.
// `PathPrefix` 없이는 `http://<server>/static/static/image.png`와 같은 URL로 액세스해야 합니다.
app.Use("/static", filesystem.New(filesystem.Config{
Root: http.FS(embedDirStatic),
PathPrefix: "static",
Browse: true,
}))
log.Fatal(app.Listen(":3000"))
}
// 특정 파일을 제공하는 라우트 정의
app.Get("/download", func(c *fiber.Ctx) error {
// SendFile 함수를 사용하여 파일 제공
err := filesystem.SendFile(c, http.Dir("your/filesystem/root"), "path/to/your/file.txt")
if err != nil {
// 오류 처리, 예: 404 Not Found 응답 반환
return c.Status(fiber.StatusNotFound).SendString("File not found")
}
return nil
})
// Fiber의 내장 미들웨어를 사용하여 "build" 디렉토리에서 정적 파일 제공
app.Use("/", filesystem.New(filesystem.Config{
Root: http.FS(f), // 정적 파일의 루트 디렉토리 지정
PathPrefix: "build", // 정적 파일이 제공되는 경로 접두사 정의
}))
// 다른 모든 라우트(와일드카드 "*")의 경우 "build" 디렉토리에서 "index.html" 파일 제공
app.Use("*", func(ctx *fiber.Ctx) error {
return filesystem.SendFile(ctx, http.FS(f), "build/index.html")
})