Skip to content

Commit 5078782

Browse files
committed
attachment support.
1 parent d2d9c31 commit 5078782

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

middleware/filesystem/filesystem.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ type Config struct {
4242
// Optional. Default: "index.html"
4343
Index string `json:"index"`
4444

45+
// When set to true, enables direct download for files.
46+
//
47+
// Optional. Default: false.
48+
Download bool `json:"download"`
49+
4550
// The value for the Cache-Control HTTP-header
4651
// that is set on the file response. MaxAge is defined in seconds.
4752
//
@@ -197,6 +202,11 @@ func New(config ...Config) fiber.Handler {
197202
c.Set(fiber.HeaderLastModified, modTime.UTC().Format(http.TimeFormat))
198203
}
199204

205+
// Sets the response Content-Disposition header to attachment if the Download option is true and if it's a file
206+
if cfg.Download && !stat.IsDir() {
207+
c.Attachment()
208+
}
209+
200210
if method == fiber.MethodGet {
201211
if cfg.MaxAge > 0 {
202212
c.Set(fiber.HeaderCacheControl, cacheControlStr)

middleware/filesystem/filesystem_test.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ func Test_FileSystem(t *testing.T) {
107107
url: "/spatest/doesnotexist",
108108
statusCode: 200,
109109
contentType: "text/html",
110-
}, /******/
110+
},
111111
{
112112
name: "PathPrefix should be applied",
113113
url: "/prefix/fiber.png",
@@ -145,6 +145,22 @@ func Test_FileSystem_Next(t *testing.T) {
145145
utils.AssertEqual(t, fiber.StatusNotFound, resp.StatusCode)
146146
}
147147

148+
// go test -run Test_FileSystem_Download
149+
func Test_FileSystem_Download(t *testing.T) {
150+
app := fiber.New()
151+
app.Use(New(Config{
152+
Root: os.DirFS("../../.github/testdata/fs"),
153+
Download: true,
154+
}))
155+
156+
resp, err := app.Test(httptest.NewRequest("GET", "/img/fiber.png", nil))
157+
utils.AssertEqual(t, nil, err, "app.Test(req)")
158+
utils.AssertEqual(t, 200, resp.StatusCode, "Status code")
159+
utils.AssertEqual(t, false, resp.Header.Get(fiber.HeaderContentLength) == "")
160+
utils.AssertEqual(t, "image/png", resp.Header.Get(fiber.HeaderContentType))
161+
utils.AssertEqual(t, `attachment`, resp.Header.Get(fiber.HeaderContentDisposition))
162+
}
163+
148164
func Test_FileSystem_NonGetAndHead(t *testing.T) {
149165
app := fiber.New()
150166

0 commit comments

Comments
 (0)