From 0133d9c331b84c1e4331f60d21e621e055ca8602 Mon Sep 17 00:00:00 2001 From: Fenny <25108519+Fenny@users.noreply.github.com> Date: Sun, 15 Mar 2020 14:00:03 +0100 Subject: [PATCH] Add StaticConfig --- app.go | 23 +++++++++++++++++++++-- router.go | 13 +++++++++++-- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/app.go b/app.go index 914255ea..5b1c58b8 100644 --- a/app.go +++ b/app.go @@ -115,9 +115,28 @@ func (app *App) Group(prefix string, handlers ...func(*Ctx)) *Group { } } +// StaticConfig represents settings for serving static files +type StaticConfig struct { + // Transparently compresses responses if set to true + // This works differently than the github.com/gofiber/compression middleware + // The server tries minimizing CPU usage by caching compressed files. + // It adds ".fiber.gz" suffix to the original file name. + // Optional. Default value false + Compress bool + // Enables byte range requests if set to true. + // Optional. Default value false + ByteRange bool + // Enable directory browsing. + // Optional. Default value false. + Browse bool + // Index file for serving a directory. + // Optional. Default value "index.html". + Index string +} + // Static : https://fiber.wiki/application#static -func (app *App) Static(prefix, root string) *App { - app.registerStatic(prefix, root) +func (app *App) Static(prefix, root string, config ...StaticConfig) *App { + app.registerStatic(prefix, root, config...) return app } diff --git a/router.go b/router.go index 3ebf835e..abfe5a0c 100644 --- a/router.go +++ b/router.go @@ -258,7 +258,7 @@ func (app *App) registerWebSocket(method, path string, handle func(*Ctx)) { }) } -func (app *App) registerStatic(prefix, root string) { +func (app *App) registerStatic(prefix, root string, config ...StaticConfig) { // Cannot have an empty prefix if prefix == "" { prefix = "/" @@ -303,13 +303,22 @@ func (app *App) registerStatic(prefix, root string) { Compress: false, CompressedFileSuffix: ".fiber.gz", CacheDuration: 10 * time.Second, - IndexNames: []string{"index.html", "index.htm"}, + IndexNames: []string{"index.html"}, PathRewrite: fasthttp.NewPathPrefixStripper(stripper), PathNotFound: func(ctx *fasthttp.RequestCtx) { ctx.Response.SetStatusCode(404) ctx.Response.SetBodyString("Not Found") }, } + // Set config if provided + if len(config) > 0 { + fs.Compress = config[0].Compress + fs.AcceptByteRange = config[0].ByteRange + fs.GenerateIndexPages = config[0].Browse + if config[0].Index != "" { + fs.IndexNames = []string{config[0].Index} + } + } fileHandler := fs.NewRequestHandler() app.routes = append(app.routes, &Route{ isMiddleware: true,