diff --git a/docs/api/ctx.md b/docs/api/ctx.md index fdd473aacc..b1e14f2d6d 100644 --- a/docs/api/ctx.md +++ b/docs/api/ctx.md @@ -1710,6 +1710,10 @@ app.Get("/file-with-url-chars", func(c *fiber.Ctx) error { }) ``` +:::info +For sending files from embedded file system [this functionality](./middleware/filesystem.md#sendfile) can be used +::: + ## SendStatus Sets the status code and the correct status message in the body, if the response body is **empty**. diff --git a/docs/api/middleware/filesystem.md b/docs/api/middleware/filesystem.md index 38e3622db7..bbeff14bf7 100644 --- a/docs/api/middleware/filesystem.md +++ b/docs/api/middleware/filesystem.md @@ -253,3 +253,48 @@ var ConfigDefault = Config{ ContentTypeCharset: "", } ``` + +## Utils + +### SendFile + +Serves a file from an [HTTP file system](https://pkg.go.dev/net/http#FileSystem) at the specified path. + +```go title="Signature" title="Signature" +func SendFile(c *fiber.Ctx, filesystem http.FileSystem, path string) error +``` +Import the middleware package that is part of the Fiber web framework + +```go +import ( + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/filesystem" +) +``` + +```go title="Example" +// 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 +}) +``` + +```go title="Example" +// 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") +}) +``` diff --git a/middleware/filesystem/filesystem.go b/middleware/filesystem/filesystem.go index ea23ab05cf..1a6d2b2a79 100644 --- a/middleware/filesystem/filesystem.go +++ b/middleware/filesystem/filesystem.go @@ -219,7 +219,9 @@ func New(config ...Config) fiber.Handler { } } -// SendFile ... +// SendFile serves a file from an HTTP file system at the specified path. +// It handles content serving, sets appropriate headers, and returns errors when needed. +// Usage: err := SendFile(ctx, fs, "/path/to/file.txt") func SendFile(c *fiber.Ctx, filesystem http.FileSystem, path string) error { file, err := filesystem.Open(path) if err != nil {