Documentation
¶
Overview ¶
Package fileserver serves static files from a directory, an embed.FS or any fs.FS, through the New controller or the Handler function.
A directory given as a string is served through http.Dir, which checks the request path as text but follows a symbolic link inside the directory that points outside it. To serve only what is under the directory, pass the fs.FS of an os.Root instead:
root, err := os.OpenRoot("./assets")
// handle err
app.Router("/static", fileserver.New(root.FS(), fileserver.Options{}))
The root holds the directory open for the life of the process, so a deploy that replaces the directory keeps serving the old one until restart, and a link that leaves the root answers 404.
Index ¶
- Variables
- func Abs(path string) string
- func BlockHidden(_ *context.Context, name string) bool
- func DirList(ctx *context.Context, dirOptions Options, dirName string, dir http.File) error
- func DirectoryExists(dir string) bool
- func Favicon(favPath string) router.Controller
- func FormatBytes(b int64) string
- func Handler(fileSystemOrDirectory any, options Options) context.Handler
- func IsHidden(file os.FileInfo) bool
- func New(fileSystemOrDirectory any, options Options) router.Controller
- func PrefixDir(prefix string, fs http.FileSystem) http.FileSystem
- func PrefixFS(fileSystem fs.FS, dir string) (fs.FS, error)
- func StripPrefix(prefix string, h context.Handler) context.Handler
- func TypeByExtension(ext string) string
- func TypeByFilename(fullFilename string) string
- func WebDAV(webdavHandler http.Handler) router.Controller
- type Attachments
- type DirCacheOptions
- type DirListFunc
- type DirListRichOptions
- type Options
Constants ¶
This section is empty.
Variables ¶
var ( // MatchImagesAssets is a simple regex expression // that can be passed to the Options.Cache.CompressIgnore field // in order to skip compression on already-compressed file types // such as images and pdf. MatchImagesAssets = regexp.MustCompile("((.*).pdf|(.*).jpg|(.*).jpeg|(.*).gif|(.*).tif|(.*).tiff)$") // MatchCommonAssets is a simple regex expression which // can be used on `Options.PushTargetsRegexp`. // It will match and Push // all available js, css, font and media files. // Ideal for Single Page Applications. MatchCommonAssets = regexp.MustCompile("((.*).js|(.*).css|(.*).ico|(.*).png|(.*).ttf|(.*).svg|(.*).webp|(.*).gif)$") )
var DefaultOptions = Options{ IndexName: indexName, PushTargets: make(map[string][]string), PushTargetsRegexp: make(map[string]*regexp.Regexp), Cache: DirCacheOptions{ Enable: false, CompressMinSize: 300, Encodings: []string{"gzip", "deflate", "br", "snappy", "s2", "zstd"}, Verbose: 1, }, ShowList: false, DirList: DirListRich(DirListRichOptions{ Tmpl: DirListRichTemplate, TmplName: "dirlist", }), Attachments: Attachments{ Enable: false, Limit: 0, Burst: 0, }, AssetValidator: nil, SPA: false, }
DefaultOptions holds the default settings for `New` and `Handler`.
var DirListRichTemplate = template.Must(template.New("dirlist"). Funcs(template.FuncMap{ "formatBytes": FormatBytes, }).Parse(` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{.Title}}</title> <style> a { padding: 8px 8px; text-decoration:none; cursor:pointer; color: #10a2ff; } table { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height: 100%; width: 100%; border-collapse: collapse; border-spacing: 0; empty-cells: show; border: 1px solid #cbcbcb; } table caption { color: #000; font: italic 85%/1 arial, sans-serif; padding: 1em 0; text-align: center; } table td, table th { border-left: 1px solid #cbcbcb; border-width: 0 0 0 1px; font-size: inherit; margin: 0; overflow: visible; padding: 0.5em 1em; } table thead { background-color: #10a2ff; color: #fff; text-align: left; vertical-align: bottom; } table td { background-color: transparent; } .table-odd td { background-color: #f2f2f2; } .table-bordered td { border-bottom: 1px solid #cbcbcb; } .table-bordered tbody > tr:last-child > td { border-bottom-width: 0; } </style> </head> <body> <table class="table-bordered table-odd"> <thead> <tr> <th>#</th> <th>Name</th> <th>Size</th> </tr> </thead> <tbody> {{ range $idx, $file := .Files }} <tr> <td>{{ $idx }}</td> {{ if $file.Download }} <td><a href="{{ $file.Path }}" title="{{ $file.ModTime }}" download>{{ $file.Name }}</a></td> {{ else }} <td><a href="{{ $file.Path }}" title="{{ $file.ModTime }}">{{ $file.Name }}</a></td> {{ end }} {{ if $file.Info.IsDir }} <td>Dir</td> {{ else }} <td>{{ formatBytes $file.Info.Size }}</td> {{ end }} </tr> {{ end }} </tbody> </table> </body></html> `))
DirListRichTemplate is the html template the `DirListRich` function is using to render the directories and files.
var WebDAVMethods = [...]string{
"OPTIONS",
"GET",
"HEAD",
"POST",
"DELETE",
"PUT",
"MKCOL",
"COPY",
"MOVE",
"LOCK",
"UNLOCK",
"PROPFIND",
"PROPPATCH",
"LINK",
"UNLINK",
"PURGE",
"VIEW",
}
WebDAVMethods contains a list of WebDAV HTTP Verbs.
Functions ¶
func Abs ¶
Abs calls filepath.Abs but ignores the error and returns the original value if any error occurred.
func BlockHidden ¶
BlockHidden is an AssetValidator that denies access to hidden files and directories: any request whose path contains a dot-prefixed segment such as ".git", ".env" or ".htpasswd". Wire it into Options.AssetValidator to keep sensitive dotfiles from being served (they are served by default):
fileserver.New(dir, fileserver.Options{AssetValidator: fileserver.BlockHidden})
It returns false (deny) for hidden paths and true otherwise. Note it also blocks conventional dot-directories such as ".well-known"; compose your own validator on top of it if you need to allow specific ones.
func DirList ¶
DirList is a `DirListFunc` which renders directories and files in html, but plain, mode. See `DirListRich` for more.
func DirectoryExists ¶
DirectoryExists returns true if a directory(or file) exists, otherwise false
func Favicon ¶
func Favicon(favPath string) router.Controller
Favicon returns a Controller which caches and serves a favicon file. Accepts the "favPath" which is the system path of the __.ico file. Usage:
app.Router("/", fileserver.Favicon("./path/to/favicon.ico"))
This will serve the ./path/to/favicon.ico to the "/favicon.ico" request path on GET and HEAD HTTP Methods.
func FormatBytes ¶
FormatBytes returns a string representation of the "b" bytes.
func Handler ¶
Handler returns a Handler which serves files from a specific file system. The first parameter is the file system, if it's a `http.Dir` the files should be located near the executable program. The second parameter is the settings that the caller can use to customize the behavior.
SECURITY: dotfiles ARE served by default.
Pointing this at a directory that also holds ".git", ".env" or ".htpasswd" publishes them. Set Options.AssetValidator to `BlockHidden` to deny any path containing a dot-prefixed segment. A warning is logged at startup when the served root obviously contains such files and no validator is configured.
Examples can be found at: https://github.com/kataras/iris/tree/main/_examples/16-advanced/file-server.
func IsHidden ¶
IsHidden checks a file is hidden or not.
On Windows it reads the FILE_ATTRIBUTE_HIDDEN bit when the FileInfo carries real Win32 attributes, and falls back to the dot-prefix convention otherwise.
Note(@kataras): the fallback is not cosmetic. This runs at request time for every entry of a listed directory, and the previous reflection-based form assumed Sys() always returned a *syscall.Win32FileAttributeData. It is nil for embed.FS entries and it is this package's own *fileInfo for a cached file system, so the old code panicked - reflect.ValueOf(nil).Elem(), or .Uint() on a zero Value - and took down the request, or the process when the listing ran from a goroutine.
func New ¶
func New(fileSystemOrDirectory any, options Options) router.Controller
New returns a new file server controller. It registers the necessary routes to serve files from the provided file system or directory through the `Handler` package-level function. The "fileSystemOrDirectory" can be a physical system directory or an embedded one (resolved by context.ResolveHTTPFS). Available "fileSystemOrDirectory" types:
- http.FileSystem
- embed.FS
- fs.FS
- string (a directory path)
The "options" can be used to customize the behavior of the file server. Usage:
app.Router("/static", fileserver.New("./assets", fileserver.Options{
IndexName: "index.html",
ShowList: true,
}))
func PrefixDir ¶
func PrefixDir(prefix string, fs http.FileSystem) http.FileSystem
PrefixDir returns a new FileSystem that opens files by adding the given "prefix" to the directory tree of "fs".
Useful when having templates and static files in the same bindata AssetFile method. This way you can select which one to serve as static files and what for templates.
func StripPrefix ¶
StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error.
Usage: fileserver := Handler("./static_files", Options {...}) h := StripPrefix("/static", fileserver) app.Get("/static/{file:path}", h) app.Head("/static/{file:path}", h)
func TypeByExtension ¶
TypeByExtension returns the MIME type associated with the file extension ext. The extension ext should begin with a leading dot, as in ".html". When ext has no associated type, TypeByExtension returns "".
It answers from the framework's extended MIME table, the one the file server itself uses. Importing this package also registers that table with the standard library's mime package, so mime.TypeByExtension knows these extensions too.
func TypeByFilename ¶
TypeByFilename is like TypeByExtension but receives a full filename path instead of just the extension.
func WebDAV ¶
func WebDAV(webdavHandler http.Handler) router.Controller
WebDAV returns a new WebDAV controller. Usage:
import "golang.org/x/net/webdav"
webdavHandler := &webdav.Handler{
FileSystem: webdav.Dir("./"),
LockSystem: webdav.NewMemLS(),
Logger: func(r *http.Request, err error) {
if err != nil {
app.Logger().Error(err)
}
},
}
app.Router("/", WebDAV(webdavHandler))
app.Listen(":8080")
Test with cURL or postman:
- List files: curl --location --request PROPFIND 'http://localhost:8080'
- Get File: curl --location --request GET 'http://localhost:8080/test.txt'
- Upload File: curl --location --request PUT 'http://localhost:8080/newfile.txt' \ --header 'Content-Type: text/plain' \ --data-raw 'This is a new file!'
- Copy File: curl --location --request COPY 'http://localhost:8080/test.txt' \ --header 'Destination: newdir/test.txt'
- Create New Directory: curl --location --request MKCOL 'http://localhost:8080/anewdir/'
Types ¶
type Attachments ¶
type Attachments struct {
// Set to true to enable the files to be downloaded and
// saved locally by the client, instead of serving the file.
Enable bool
// Options to send files with a limit of bytes sent per second.
Limit float64
Burst int
// Use this function to change the sent filename.
NameFunc func(systemName string) (attachmentName string)
}
Attachments options for files to be downloaded and saved locally by the client. See `Options`.
type DirCacheOptions ¶
type DirCacheOptions struct {
// Enable or disable cache.
Enable bool
// Minimum content size for compression in bytes.
CompressMinSize int64
// Ignore compress files that match this pattern.
CompressIgnore *regexp.Regexp
// The available sever's encodings to be negotiated with the client's needs,
// common values: gzip, br, zstd.
Encodings []string
// If greater than zero then prints information about cached files to the stdout.
// If it's 1 then it prints only the total cached and after-compression reduced file sizes
// If it's 2 then it prints it per file too.
Verbose uint8
}
DirCacheOptions holds the options for the cached file system. See `Options` structure for more.
type DirListFunc ¶
type DirListFunc func(ctx *context.Context, dirOptions Options, dirName string, dir http.File) error
DirListFunc is the function signature for customizing directory and file listing. See `DirList` and `DirListRich` functions for its implementations.
func DirListRich ¶
func DirListRich(opts ...DirListRichOptions) DirListFunc
DirListRich is a `DirListFunc` which can be passed to `Options.DirList` field to override the default file listing appearance. See `DirListRichTemplate` to modify the template, if necessary.
type DirListRichOptions ¶
type DirListRichOptions struct {
// If not nil then this template's "dirlist" is used to render the listing page.
Tmpl *template.Template
// If not empty then this view file is used to render the listing page.
// The view should be registered with `view.Render`.
// E.g. "dirlist.html"
TmplName string
}
DirListRichOptions the options for the `DirListRich` helper function.
type Options ¶
type Options struct {
// Defaults to "/index.html", if request path is ending with **/*/$IndexName
// then it redirects to **/*(/).
// That index handler is registered automatically
// by the framework unless but it can be overridden.
// See `RedirectToIndex` to turn that redirect around.
IndexName string
// RedirectToIndex serves the index file at its own URL (**/*/$IndexName)
// and redirects a directory requested without a trailing slash to that URL,
// instead of redirecting the index file to its directory.
// Enable it for index pages with relative links (css/app.css, page2.html):
// the router removes the trailing slash of a directory URL,
// so a browser resolves them against the parent path.
//
// The redirect of the directory is a 302 (Found), so no browser keeps it
// after the option is turned off again.
// A directory that has no index file is not redirected.
// It has no effect when `SPA` is true, where the index is served on paths
// of any depth and a client-side router expects the directory URL,
// or when `IndexName` is empty.
// On a site that was live without it, a browser that cached the redirect
// of an index file to its directory loops until that entry is gone.
//
// Defaults to false.
RedirectToIndex bool
// PushTargets filenames (map's value) to
// be served without additional client's requests (HTTP/2 Push)
// when a specific request path (map's key WITHOUT prefix)
// is requested and it's not a directory (it's the `IndexName` file).
//
// Example:
// "/": {
// "favicon.ico",
// "js/main.js",
// "css/main.css",
// }
PushTargets map[string][]string
// PushTargetsRegexp like `PushTargets` but accepts regexp which
// is compared against all files under a directory (recursively).
// The `IndexName` should be set.
//
// Example:
// "/": regexp.MustCompile("((.*).js|(.*).css|(.*).ico)$")
// See `iris.MatchCommonAssets` too.
PushTargetsRegexp map[string]*regexp.Regexp
// Cache to enable in-memory cache and pre-compress files.
Cache DirCacheOptions
// List the files inside the current requested
// directory if `IndexName` not found.
ShowList bool
// If `ShowList` is true then this function will be used instead
// of the default one to show the list of files
// of a current requested directory(dir).
// See `DirListRich` package-level function too.
DirList DirListFunc
// Show hidden files or directories or not when `ShowList` is true.
ShowHidden bool
// Files downloaded and saved locally.
Attachments Attachments
// Optional validator that loops through each requested resource.
AssetValidator func(ctx *context.Context, name string) bool
// If enabled then the router will render the index file on any not-found file
// instead of firing the 404 error code handler.
// Make sure the `IndexName` field is set.
SPA bool
}
Options contains the settings that `New` and `Handler` can use to serve files. See `DefaultOptions`.