Skip to content

Commit

Permalink
improve sendFile documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
ReneWerner87 committed Oct 6, 2023
1 parent 0d33546 commit 59409f3
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
4 changes: 4 additions & 0 deletions docs/api/ctx.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**.
Expand Down
45 changes: 45 additions & 0 deletions docs/api/middleware/filesystem.md
Original file line number Diff line number Diff line change
Expand Up @@ -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")
})
```
4 changes: 3 additions & 1 deletion middleware/filesystem/filesystem.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 59409f3

Please sign in to comment.