Static
The Static middleware serves assets such as images, CSS, and JavaScript. It answers GET and HEAD requests and passes every other method to the next handler.
By default, it serves index.html when a directory is requested. Customize this behavior in the Config options.
Signatures
func New(root string, cfg ...Config) fiber.HandlerExamples
Import the package:
import(
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/static"
)Serving files from a directory
app.Get("/*", static.New("./public"))Test
curl http://localhost:3000/hello.html
curl http://localhost:3000/css/style.cssServing files from a directory with Use
app.Use("/", static.New("./public"))Test
curl http://localhost:3000/hello.html
curl http://localhost:3000/css/style.cssServing a single file
app.Use("/static", static.New("./public/hello.html"))Test
curl http://localhost:3000/static # will show hello.html
curl http://localhost:3000/static/john/doe # will show hello.htmlServing files using os.DirFS
app.Get("/files*", static.New("", static.Config{
FS: os.DirFS("files"),
Browse: true,
}))Test
curl http://localhost:3000/files/css/style.css
curl http://localhost:3000/files/index.htmlServing files using embed.FS
//go:embed path/to/files
var myfiles embed.FS
app.Get("/files*", static.New("path/to/files", static.Config{
FS: myfiles,
Browse: true,
}))With FS set, the first argument names the directory inside the file system to serve, and "" serves its root. An embed.FS keeps the path it embedded, so pass that path.
Test
curl http://localhost:3000/files/css/style.css
curl http://localhost:3000/files/index.htmlServing pre-compressed files
app := fiber.New(fiber.Config{
CompressedFileSuffixes: map[string]string{
"gzip": ".gz",
"br": ".br",
"zstd": ".zst",
},
})
app.Get("/assets*", static.New("./dist", static.Config{
Compress: true,
}))With Compress, a file that has a compressed copy next to it under the suffix of the requested encoding, such as app.js.gz for app.js, is served from that copy instead of being compressed again. Only a missing copy is compressed and written next to the file.
- The suffixes are set on the app with
CompressedFileSuffixes, not on the middleware. Setgzip,brandzstd, each to a different suffix: with one missing, the whole map is ignored, and copies are read and written under.fasthttp.gz,.fasthttp.brand.fasthttp.zst. - A copy whose original was modified a second or more after it counts as stale and is overwritten with a new one, so compress the files after the build writes them.
- Without
Compress, the original is served and the copies are not used.
Test
curl -H "Accept-Encoding: gzip" --compressed http://localhost:3000/assets/app.jsSPA (Single Page Application)
app.Use("/web", static.New("", static.Config{
FS: os.DirFS("dist"),
}))
app.Get("/web*", func(c fiber.Ctx) error {
return c.SendFile("dist/index.html")
})Test
curl http://localhost:3000/web/css/style.css
curl http://localhost:3000/web/index.html
curl http://localhost:3000/webTo define static routes using Get, append the wildcard (*) operator at the end of the route. Under a /static* or /static+ route the rest of the path must start at a segment boundary, so /static-v2/app.js or /staticapp.js are no longer served; only /static and paths below /static/ are.
A route whose first parameter is a wildcard strips the text before it, as /static* does: under /assets/*.js the path /assets/app.js serves app.js. After a named parameter, a directory root takes the file name from the wildcard that ends the route: under /:lang/* the path /en/app.js serves app.js. A parameter there that matched an empty segment, as in //app.js under /:lang?/*, is answered with 404 Not Found, as an empty first segment is on a root mount. A route with a named parameter and no trailing wildcard, such as app.Use("/:tenant", ...) or a sub-app mounted on it, does not tell where the file name starts, so a directory root serves nothing there; register it as Get("/*", ...) inside the sub-app instead. A root that is a single file is served on such a route.
The file server resolves the path the router matched. A handler that changes the path before static on the same route, such as a rewrite registered in the same Use, does not move it off that route: a path that no longer starts with the route's prefix, or no longer matches the pattern before the wildcard of a route such as /:lang/*, is answered with 404 Not Found. Fiber normalizes request paths before routing (see Path normalization), so middleware mounted on /static/private also guards /static/%70rivate/secret.txt and /static/x/../private/secret.txt. With Browse, the title and links of a directory listing follow that path as well. On a route whose prefix holds a parameter, such as /:lang/*, each listing links below its own prefix, so Browse turns the file cache off for that route, files included, as a negative CacheDuration would. A routed prefix there that holds %, \, ?, # or a control character is answered with 404 Not Found, since fasthttp decodes the prefix when it writes the links and a browser drops a tab or line break from them.
Escapes the router leaves encoded, such as %20, %40 or %25, also remain encoded for file lookup. This keeps routing, including path-scoped authorization middleware, and static-file resolution on the same resource name. Consequently, /static/hello%20world.txt does not serve hello world.txt; enable UnescapePath when encoded spellings should resolve to decoded file names.
A path that cannot name a file inside the root is answered with 404 Not Found:
- an escape that represents a slash, a backslash or a control character, so
/static/private%2Fsecret.txtnever reachesprivate/secret.txtunlessUnescapePathdecodes it for the router as well; - a malformed escape such as
%zz; - an escape of an unreserved character. The router decodes every one of those when it normalizes a path, so one still in the routed path can only have been forged by a stray
%, and it is rejected rather than decoded a second time:/static/%%370rivate/secret.txtnever opensprivate/secret.txt; - an empty,
.or..segment, so/static//private/secret.txtis not found; - for a root on the operating system's file system, a first segment that starts with a drive letter such as
C:.
With UnescapePath enabled the router has already decoded every escape, so a malformed escape is an ordinary part of the name: /static/100%zz.txt names 100%zz.txt.
A root mount, such as app.Use(static.New(dir)) or app.Get("/*", static.New(dir)), refuses a path whose first segment is empty too, whether it serves a directory or a single file. The router keeps the empty first segment of //private/secret.txt apart from /private/secret.txt, so a root mount answers it with 404 Not Found instead of serving anything for a path that middleware mounted on /private never saw. That includes any spelling the router turns into such a path, such as /.//private/secret.txt or, with UnescapePath enabled, /%2Fprivate/secret.txt.
The router reads /static/private and /static/private/ as one path, and so does the file server: either spelling serves the directory's index, or a file of that name. With StrictRouting enabled the router keeps the two apart and the file server follows the router, while middleware registered with Use on /static/private/ still runs for /static/private. A directory, the mount point /static included, is then served for the spelling that ends in a slash only, and the other one is redirected to it with 302 Found. A file is served for the spelling without the slash only, so /static/secret.txt/ is answered with 404 Not Found.
A root that is a single file looks nothing up by the path, so it serves its file for every other path the route matches, whatever its spelling, and no spelling of a path can select another file. An empty segment further in is an ordinary part of a name there, as in /web/https://example.com.
A client that puts a doubled slash in front of a path, such as a base URL that ends in / joined to a path that starts with /, gets 404 Not Found from a root mount. To keep serving it, collapse the slash with the Rewrite middleware before any middleware that matches a path prefix runs. The middleware registered after it, one guarding /private included, then sees /private/secret.txt:
app.Use(rewrite.New(rewrite.Config{
RuleList: []rewrite.Rule{{From: "//*", To: "/$1"}},
}))The file server opens the name the router matched, so it is only as strict as the filesystem underneath. Windows and FAT volumes drop the trailing dots and spaces of a path component when they open it, so /static/private./secret.txt would reach private/secret.txt without passing middleware mounted on /static/private; the file server answers such a segment with 404 Not Found on every OS and for every root, since neither the volume nor what backs an fs.FS is known. The router folds the case of ASCII letters only, while a case-folding filesystem also opens secret for ลฟecret (U+017F), and 8.3 short names such as PRIVAT~1 open a long name; a path that holds a character such a filesystem can open as ASCII or drop, or a ~ followed by a digit, is therefore answered with 404 Not Found, a real file named like report~1.txt or straรe.txt included. Those characters are ลฟ, ฤฑ, ฤฐ and the Kelvin sign (U+212A), whose upper or lower case is an ASCII letter, ร, แบ and the ligatures U+FB00 to U+FB06, whose case folding is ASCII (ss, fi, st), U+037E and U+1FEF, which normalize to ; and a backtick, and the default ignorable characters, which the case folding of Linux (ext4 and f2fs directories with casefold) leaves out of the name, as HFS+ does with some of them. Those include the soft hyphen, the zero-width space, the zero-width non-joiner and joiner (U+200C, U+200D) that Persian and Indic words and most emoji sequences hold, and the variation selectors U+FE00 to U+FE0F, so a file named with one of them is not served from a directory root, an embed.FS included; rename it, or serve it on a route of its own as a file root or with SendFile. A filesystem that also applies compatibility normalization, such as ZFS with normalization=formKC, opens fullwidth and other styled letters (๏ฝecret) as ASCII as well; those are not refused, since they are common in names such as Japanese ones, so keep guarded directories off such a root. A non-ASCII name in another case (CAFร for cafรฉ) or another Unicode normalization (NFD for NFC) can still open the same file on a filesystem that folds case or normalizes names, so guard directories by ASCII names. Case is a different matter: on a case-insensitive filesystem (Windows, and macOS by default) /static/PRIVATE/secret.txt opens private/secret.txt, and with CaseSensitive enabled the router keeps the two apart, so middleware mounted on /static/private does not run. Leave CaseSensitive off (the default) for a static root with guarded directories, or serve it from a case-sensitive filesystem.
Config
| Property | Type | Description | Default |
|---|---|---|---|
| Next | func(fiber.Ctx) bool | Next defines a function to skip this middleware when it returns true. | nil |
| FS | fs.FS | FS is the file system to serve the static files from. You can use interfaces compatible with fs.FS like embed.FS, os.DirFS etc. With FS set, the root argument of New names a directory inside it, and "" serves its root. | nil |
| Compress | bool | When set to true, the server tries minimizing CPU usage by caching compressed files. The middleware will compress the response using gzip, brotli, or zstd compression depending on the Accept-Encoding header. This works differently than the github.com/gofiber/compression middleware. | false |
| ByteRange | bool | When set to true, enables byte range requests. A request for several ranges, or whose If-Range does not match, gets the whole file. | false |
| Browse | bool | When set to true, enables directory browsing. | false |
| Download | bool | When set to true, enables direct download. | false |
| AllowSymlinksOutsideRoot | bool | When set to true, symbolic links that leave the root, and absolute ones, are followed. Has no effect with FS. | false |
| IndexNames | []string | The names of the index files for serving a directory. | []string{"index.html"} |
| CacheDuration | time.Duration | Expiration duration for inactive file handlers. Use a negative time.Duration to disable it. | 10 * time.Second |
| MaxAge | int | The max-age, in seconds, of the Cache-Control HTTP-header that is set on the file response unless the response already has one. | 0 |
| ModifyResponse | fiber.Handler | ModifyResponse defines a function that allows you to alter the response. | nil |
| NotFoundHandler | fiber.Handler | NotFoundHandler defines a function to handle when the path is not found. | nil |
When Download is enabled, the response of a served file includes a Content-Disposition header with the requested filename, while the Content-Type the file server detected is kept. Non-ASCII names use the filename* parameter as defined by RFC 6266 and RFC 8187. A request for a missing file falls through to the next handler without the header.
MaxAge only applies to successful responses; an error such as 416 Range Not Satisfiable carries no Cache-Control. It sends max-age=<MaxAge> without public, which would let a shared cache, the cache middleware included, store a file sent with a cookie, and it keeps a Cache-Control that middleware in front of static set, such as private, no-store on a guarded directory. Write public in ModifyResponse for files every client may share. A handler registered on several routes serves each under that route's own prefix. Outside a route, as under adaptor.FiberHandler or in an ErrorHandler for a request that no route matched, the whole path stands for the prefix, so a file root serves its file and a directory root its index, from one file server per app. No handler follows there, so a miss, or a request static does not serve, returns fiber.ErrNotFound instead of calling Next. Once a handler has run, global middleware registered with app.Use included, the ErrorHandler sees that handler's route: static serves the path below that route's prefix and calls Next on a miss, as on the route itself.
A directory without an index file is a miss like a missing file: the next handler runs with the response headers that earlier middleware set.
A root on disk must be named: New panics on an empty root, which would be the filesystem root, so an unset variable cannot expose every file the process can read; use "." for the working directory. With FS, an empty root is the root of that file system. A root on disk is confined: a relative symbolic link that stays inside it is followed, while one that leaves it, and an absolute link even when it points inside, is handled like a missing file. Set AllowSymlinksOutsideRoot when such links are intended, for example a shared asset directory or a build tool that writes absolute links. With Compress, the compressed copy of a file reached through a linked directory is written into that directory. A file root, and a root given through FS, are not confined this way.
You can set CacheDuration config property to -1 to disable caching.
Default Config
var ConfigDefault = Config{
IndexNames: []string{"index.html"},
CacheDuration: 10 * time.Second,
}