fileserver

package
v14.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 23 Imported by: 0

README

Iris File Server

This controller serves static files: images, stylesheets, scripts, downloads. The files can sit in a directory on disk or be compiled into the binary through an embedded file system. Directory listing, caching, compression, HTTP/2 Push, single-page-application fallback and WebDAV are all options on the same controller.

Features of Iris File Server

The Iris file server offers a variety of features to handle static file serving efficiently. These features include:

  1. Serving Static Files: Serve static files from a directory or an embedded file system.
  2. Directory Listing: Optionally list the contents of directories with customizable options.
  3. File Caching: Enable in-memory caching and pre-compression of files.
  4. HTTP/2 Push: Push resources to the client without additional requests.
  5. Attachments: Serve files as downloadable attachments with optional rate limiting and filename customization.
  6. Single Page Application (SPA) Support: Serve the index file for all not-found routes.
  7. Favicon Serving: Serve a favicon file with caching.
  8. Strip Prefix: Serve files by stripping a specified prefix from the URL.
  9. WebDAV Support: Serve files with WebDAV support for remote file management.
  10. Index Pages with Relative Links: Serve a directory's index file at its own URL, so the relative links of the page load from that directory.

Installation

To use the Iris file server, you need to have the Iris framework installed. You can install Iris using the following command:

go get github.com/kataras/iris/v14@latest

Usage

Basic Setup

To use the file server, you need to import the necessary packages and configure the controller in your Iris application. Here is a basic example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	app.Router("/static", fileserver.New("./assets", fileserver.Options{
		IndexName: "index.html",
	}))

	app.Listen(":8080")
}
Serving Static Files

Files can come from a directory on disk or from an embedded file system. Here are examples for each:

Using a Directory Path
package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	app.Router("/static", fileserver.New("./assets", fileserver.Options{
		IndexName: "index.html",
	}))

	app.Listen(":8080")
}
Using http.FileSystem
package main

import (
	"net/http"
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	fs := http.Dir("./assets")
	app.Router("/static", fileserver.New(fs, fileserver.Options{
		IndexName: "index.html",
	}))

	app.Listen(":8080")
}
Using embed.FS
package main

import (
	"embed"
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

//go:embed assets
var embeddedFiles embed.FS

func main() {
	app := iris.New()
	app.Router("/static", fileserver.New(embeddedFiles, fileserver.Options{
		IndexName: "index.html",
	}))

	app.Listen(":8080")
}
Using fs.FS
package main

import (
	"io/fs"
	"os"
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	dirFS := os.DirFS("./assets")
	app.Router("/static", fileserver.New(dirFS, fileserver.Options{
		IndexName: "index.html",
	}))

	app.Listen(":8080")
}

A directory given as a string becomes an http.Dir. http.Dir works on the request path as text: it cleans the path before it opens anything, so a .. in /static/../secret cannot climb out of the directory. A symbolic link (or a Windows junction) that sits inside ./assets and points somewhere else is a different matter: it is followed, and the file at the other end is served. To serve only what is really under the directory, open it with os.OpenRoot and pass its fs.FS:

root, err := os.OpenRoot("./assets")
if err != nil {
	app.Logger().Fatal(err)
}
app.Router("/static", fileserver.New(root.FS(), fileserver.Options{}))

A link that leaves the root now answers 404 instead of the file it points to. This costs two things. The process holds the directory open for as long as it runs, so a deploy that replaces ./assets with a new directory keeps serving the old one until the process restarts. And a link that leaves the root is no longer served at all, which breaks a layout that relies on one on purpose, for example ./assets/shared linked to a directory outside it.

Directory Listing

The file server can optionally list the contents of directories. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	app.Router("/static", fileserver.New("./assets", fileserver.Options{
		ShowList: true,
	}))

	app.Listen(":8080")
}
Using DirList

The DirList function renders directories and files in a plain HTML format. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	app.Router("/static", fileserver.New("./assets", fileserver.Options{
		ShowList: true,
		DirList:  fileserver.DirList,
	}))

	app.Listen(":8080")
}
Using DirListRich

The DirListRich function renders directories and files in a rich HTML format with customizable templates. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	app.Router("/static", fileserver.New("./assets", fileserver.Options{
		ShowList: true,
		DirList:  fileserver.DirListRich(fileserver.DirListRichOptions{
			Tmpl:     fileserver.DirListRichTemplate,
			TmplName: "dirlist",
		}),
	}))

	app.Listen(":8080")
}
File Caching

The file server supports in-memory caching and pre-compression of files. The CompressMinSize option specifies the minimum content size for compression in bytes. Files smaller than this size will not be compressed to avoid the overhead of compressing small files, which may not provide significant benefits. The supported compression algorithms are gzip, deflate, brotli, snappy, s2 and zstd. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	app.Router("/static", fileserver.New("./assets", fileserver.Options{
		Cache: fileserver.DirCacheOptions{
			Enable:          true,
			CompressMinSize: 300, // Minimum content size for compression in bytes
			Encodings:       []string{"gzip", "deflate", "br", "snappy", "s2", "zstd"},
			Verbose:         1,
		},
	}))

	app.Listen(":8080")
}
HTTP/2 Push

HTTP/2 Push is a feature that allows the server to send resources to the client proactively, without the client having to request them. This can improve page load times by reducing the number of round trips required to fetch resources. You can read more about HTTP/2 Push on Wikipedia.

With HTTP/2 Push the server sends a resource the client has not asked for yet, saving a round trip. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	app.Router("/static", fileserver.New("./assets", fileserver.Options{
		PushTargets: map[string][]string{
			"/": {"favicon.ico", "js/main.js", "css/main.css"},
		},
	}))

	app.Listen(":8080")
}
Attachments

A file can be served as a download rather than rendered, with an optional transfer rate limit and a filename of your choosing. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	app.Router("/static", fileserver.New("./assets", fileserver.Options{
		Attachments: fileserver.Attachments{
			Enable: true,
			Limit:  1024, // 1 KB per second
			Burst:  2048, // Allow bursts up to 2 KB
			NameFunc: func(systemName string) string {
				return "download-" + systemName
			},
		},
	}))

	app.Listen(":8080")
}
Single Page Application (SPA) Support

The file server supports serving the index file for all not-found routes, which is useful for Single Page Applications (SPAs). Make sure to set the IndexName field. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	app.Router("/static", fileserver.New("./assets", fileserver.Options{
		SPA:       true,
		IndexName: "index.html",
	}))

	app.Listen(":8080")
}

The router removes the trailing slash of a directory URL, so the index page of ./assets/doc is served at /static/doc. From that URL a browser resolves a relative link against the parent path: it asks for css/app.css at /static/css/app.css and for page2.html at /static/page2.html. Root-relative links such as /static/doc/css/app.css work from any URL and need nothing.

Set RedirectToIndex to serve the index file at its own URL instead. /static/doc then redirects to /static/doc/index.html, and the relative links of the page resolve inside /static/doc/. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	app.Router("/static", fileserver.New("./assets", fileserver.Options{
		IndexName:       "index.html",
		RedirectToIndex: true,
	}))

	app.Listen(":8080")
}

The option is off by default, and it does nothing when SPA is true or IndexName is empty. A directory that has no index file is not redirected. On a site that was live without it, a browser that cached the old redirect of /static/doc/index.html to its directory can loop until that cache entry is gone.

Customizable MIME Types

Map your own MIME type onto a file extension when the default guess is wrong. Here is an example:

package main

import (
	"mime"

	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	mime.AddExtensionType(".custom", "application/custom")

	app := iris.New()
	app.Router("/static", fileserver.New("./assets", fileserver.DefaultOptions))

	app.Listen(":8080")
}
Favicon Serving

A favicon is a small icon that represents a website or web application. It is typically displayed in the browser's address bar, tab, or bookmark list. Favicons can also be used as app icons on mobile devices and tablets. The recommended size for a favicon is 16x16 pixels for browsers, but it can also include larger sizes such as 32x32, 48x48, 64x64, and 128x128 pixels for different platforms and applications.

Serve a favicon with caching in one call. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	app.Router("/", fileserver.Favicon("./assets/favicon.ico"))

	app.Listen(":8080")
}
StripPrefix

The StripPrefix function returns a handler that serves HTTP requests by removing the given prefix from the request URL's path and invoking the handler h. This is useful when you want to serve files from a specific directory but want to strip the directory prefix from the URL. Here is an example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/fileserver"
)

func main() {
	app := iris.New()
	fileserverHandler := fileserver.Handler("./static_files", fileserver.DefaultOptions)
	h := fileserver.StripPrefix("/static", fileserverHandler)

	app.Get("/static/{file:path}", h)
	app.Head("/static/{file:path}", h)

	app.Listen(":8080")
}
Differences Between New and Handler

The New and Handler functions both serve static files, but they are used in different contexts and have different purposes:

  • New: This function returns a new file server controller and registers the necessary routes to serve files from the provided file system or directory (GET, HEAD). It is used to create a complete file server with routing capabilities. It is typically used when you want to serve static files from a specific route in your Iris application.

    app.Router("/static", fileserver.New("./assets", fileserver.Options{
    	IndexName: "index.html",
    	ShowList:  true,
    }))
    
  • Handler: This function returns a handler that serves files from a specific file system. It is used to create a file server handler that can be used with custom route(s). It is typically used when you want to serve static files as part of a more complex routing setup.

    fileserverHandler := fileserver.Handler("./static_files", fileserver.DefaultOptions)
    h := fileserver.StripPrefix("/static", fileserverHandler)
    
    app.Get("/static/{file:path}", h)
    app.Head("/static/{file:path}", h)
    
WebDAV Support

WebDAV (Web Distributed Authoring and Versioning) extends HTTP with methods for creating, moving and deleting files, so a client can manage the served directory remotely. Read more about it on Wikipedia.

Here is an example of how to use WebDAV with the Iris file server:

package main

import (
    "net/http"

    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/controller/fileserver"

    "golang.org/x/net/webdav"
)

func main() {
    app := iris.New()
    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("/", fileserver.WebDAV(webdavHandler))

    app.Listen(":8080")
}
  • 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/'
    

Context Methods

ServeContent

The ServeContent method replies to the request using the content in the provided io.ReadSeeker. It handles Range requests, sets the MIME type, and handles various conditional requests.

Example
package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/rest/errors"
	"os"
	"time"
)

func main() {
	app := iris.New()

	app.Get("/content", func(ctx iris.Context) {
		file, err := os.Open("example.txt")
		if err != nil {
			errors.HandleError(ctx, err)
			return
		}
		defer file.Close()

		ctx.ServeContent(file, "example.txt", time.Now())
	})

	app.Listen(":8080")
}
ServeContentWithRate

The ServeContentWithRate method is similar to ServeContent but it can throttle the speed of reading and writing the content to the client.

Example
package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/rest/errors"
	"os"
	"time"
)

func main() {
	app := iris.New()

	app.Get("/content", func(ctx iris.Context) {
		file, err := os.Open("example.txt")
		if err != nil {
			errors.HandleError(ctx, err)
			return
		}
		defer file.Close()

		ctx.ServeContentWithRate(file, "example.txt", time.Now(), 1024, 2048) // 1 KB/s with bursts up to 2 KB
	})

	app.Listen(":8080")
}
ServeFile

The ServeFile method replies to the request with the contents of the named file or directory. Use it when you want to serve assets like CSS and JavaScript files. If the client should confirm and save the file, use the SendFile method instead.

Example
package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/rest/errors"
)

func main() {
	app := iris.New()

	app.Get("/file", func(ctx iris.Context) {
		err := ctx.ServeFile("example.txt")
		if err != nil {
			errors.HandleError(ctx, err)
		}
	})

	app.Listen(":8080")
}
ServeFileWithRate

The ServeFileWithRate method is similar to ServeFile but it can throttle the speed of reading and writing the file to the client.

Example
package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/rest/errors"
)

func main() {
	app := iris.New()

	app.Get("/file", func(ctx iris.Context) {
		err := ctx.ServeFileWithRate("example.txt", 1024, 2048) // 1 KB/s with bursts up to 2 KB
		if err != nil {
			errors.HandleError(ctx, err)
		}
	})

	app.Listen(":8080")
}
SendFile

The SendFile method sends a file as an attachment, which is downloaded and saved locally by the client. Use this method when you want the user to directly download a file, such as an uploaded file.

Example
package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/rest/errors"
)

func main() {
	app := iris.New()

	app.Get("/download", func(ctx iris.Context) {
		err := ctx.SendFile("example.txt", "downloaded_example.txt")
		if err != nil {
			errors.HandleError(ctx, err)
		}
	})

	app.Listen(":8080")
}
SendFileWithRate

The SendFileWithRate method is similar to SendFile but it can throttle the speed of reading and writing the file to the client.

Example
package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/rest/errors"
)

func main() {
	app := iris.New()

	app.Get("/download", func(ctx iris.Context) {
		err := ctx.SendFileWithRate("example.txt", "downloaded_example.txt", 1024, 2048) // 1 KB/s with bursts up to 2 KB
		if err != nil {
			errors.HandleError(ctx, err)
		}
	})

	app.Listen(":8080")
}
When to Use Serve Methods vs. Send Methods
  • Serve Methods (ServeContent, ServeContentWithRate, ServeFile, ServeFileWithRate): Use these methods when you want to serve static files like CSS, JavaScript, or HTML files directly to the client. These methods are suitable for serving assets that are part of your web application's frontend.

  • Send Methods (SendFile, SendFileWithRate): Use these methods when you want the client to download a file as an attachment. This is useful for scenarios where the user needs to download and save a file locally, such as downloading an uploaded file or exporting data.

Blocking Hidden Files (v14)

By default the file server serves dotfiles such as .git or .env when they exist in the served directory. To deny them, set fileserver.BlockHidden as the AssetValidator:

app.Router("/static", fileserver.New("./assets", fileserver.Options{
    AssetValidator: fileserver.BlockHidden,
}))

BlockHidden denies any request whose path contains a dot-prefixed segment. 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.

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

Constants

This section is empty.

Variables

View Source
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)$")
)
View Source
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`.

View Source
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.

View Source
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

func Abs(path string) string

Abs calls filepath.Abs but ignores the error and returns the original value if any error occurred.

func BlockHidden

func BlockHidden(_ *context.Context, name string) bool

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

func DirList(ctx *context.Context, dirOptions Options, dirName string, dir http.File) error

DirList is a `DirListFunc` which renders directories and files in html, but plain, mode. See `DirListRich` for more.

func DirectoryExists

func DirectoryExists(dir string) bool

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

func FormatBytes(b int64) string

FormatBytes returns a string representation of the "b" bytes.

func Handler

func Handler(fileSystemOrDirectory any, options Options) context.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

func IsHidden(file os.FileInfo) bool

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 PrefixFS

func PrefixFS(fileSystem fs.FS, dir string) (fs.FS, error)

PrefixFS same as "PrefixDir" but for `fs.FS` type.

func StripPrefix

func StripPrefix(prefix string, h context.Handler) context.Handler

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

func TypeByExtension(ext string) string

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

func TypeByFilename(fullFilename string) string

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:

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`.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL