FileSystem


Fiber를 위한 Filesystem 미들웨어는 디렉토리에서 파일을 제공할 수 있게 합니다.

Signatures

func New(config Config) fiber.Handler

Examples

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,
}))

환경(Go 1.16+)이 지원하는 경우 나열된 다른 솔루션 대신 Go Embed를 사용하는 것이 좋습니다. 이는 Go에 기본 제공되며 사용이 가장 쉽습니다.

embed

Embed는 Golang 실행 파일에 파일을 포함시키는 기본 방법입니다. Go 1.16에서 도입되었습니다.

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"))
}

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"

	// init 함수를 호출하고 데이터를 statik에 등록하려면 blank를 사용하세요
	_ "<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"))
}

Config

Property
Type
Description
Default

Next

func(*fiber.Ctx) bool

Next는 true를 반환할 때 이 미들웨어를 건너뛰는 함수를 정의합니다.

nil

Root

http.FileSystem

Root는 파일 및 디렉토리 모음에 대한 액세스를 제공하는 FileSystem입니다.

nil

PathPrefix

string

PathPrefix는 FileSystem에서 파일을 읽을 때 파일 경로에 추가할 접두사를 정의합니다.

""

Browse

bool

디렉토리 탐색을 활성화합니다.

false

Index

string

디렉토리 제공을 위한 인덱스 파일입니다.

"index.html"

MaxAge

int

파일 응답에 설정된 Cache-Control HTTP 헤더의 값입니다. MaxAge는 초 단위로 정의됩니다.

0

NotFoundFile

string

경로를 찾을 수 없는 경우 반환할 파일입니다. SPA에 유용합니다.

""

ContentTypeCharset

string

파일 응답에 설정된 Content-Type HTTP 헤더의 값입니다.

""

Default Config

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

Utils

SendFile

지정된 경로의 HTTP 파일 시스템에서 파일을 제공합니다.

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

Fiber 웹 프레임워크의 일부인 미들웨어 패키지를 가져옵니다.

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/filesystem"
)
// 특정 파일을 제공하는 라우트 정의
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")
})

Last updated