This chapter introduces the Go Iris framework and how to handle static files. Sometimes in a project, there are some static files that need to be directly exposed for user access. How should this be set up?
Iris Exposes Static Files
func main() {
app := iris.New()
// Set page icon
app.Favicon("./resources/favicon.ico")
// Set the path for static files and bind the URL route
app.HandleDir("/assets", iris.Dir("./assets"))
app.Listen(":8080")
}
The HandleDir method accepts a third optional parameter DirOptions:
type DirOptions struct {
// Default is "/index.html". If the request path ends with **/*/$IndexName, it redirects to **/*(/),
// which leads to another handler that is being served by the framework automatically registered as the index handler
// if the end-developer didn't handle it manually.
IndexName string
// PushTargets file names (values mapped) to serve without additional client requests (HTTP/2 Push) when the specific request path (key of the map without the prefix)
// requested path (the map's key without the prefix) is not a directory (is an `IndexFile`) or when should.
// PushTargetsRegexp is like `PushTargets` but it accepts a regexp which will be compared with all files under the directory (recursively).
// `IndexName` should be set.//
// Example
// "/": regexp.MustCompile("((.*).js|(.*).css|(.*).ico)$")
// See also `iris.MatchCommonAssets`.
PushTargetsRegexp map[string]*regexp.Regexp
// Caching to enable in-memory cache and pre-compressed files.
Cache DirCacheOptions
// When files should be served in a compressed state.
Compress bool
// List the files in the current request directory if `IndexName` is not found.
ShowList bool
// If `ShowList` is true, then this function will be used to display the file list of the current requested directory (dir)
// instead of the default one.
DirList DirListFunc
// Download and save to local files.
Attachments Attachments
// Optional validator to use to loop through each request's resource.
AssetValidator func(ctx *context.Context, name string) bool
}