Introduction
Serve static files from a specific directory (system physical or embedded to the application) is done by the Party.HandleDir method.
HandleDir registers a handler that serves HTTP requests with the contents of a file system (physical or embedded).
  • First parameter : the route path
  • Second parameter : the file system that needs to be served
  • Third parameter : optional, the directory options.
1
HandleDir(requestPath string, fs http.FileSystem, opts ...DirOptions) ( []*Route)
Copied!
The DirOptions structure looks like this:
1
type DirOptions struct {
2
// Defaults to "/index.html", if request path is ending with **/*/$IndexName
3
// then it redirects to **/*(/).
4
// That index handler is registered automatically
5
// by the framework unless but it can be overriden.
6
IndexName string
7
// PushTargets filenames (map's value) to
8
// be served without additional client's requests (HTTP/2 Push)
9
// when a specific request path (map's key WITHOUT prefix)
10
// is requested and it's not a directory (it's an `IndexFile`).
11
//
12
// Example:
13
// "/": {
14
// "favicon.ico",
15
// "js/main.js",
16
// "css/main.css",
17
// }
18
PushTargets map[string][]string
19
// PushTargetsRegexp like `PushTargets` but accepts regexp which
20
// is compared against all files under a directory (recursively).
21
// The `IndexName` should be set.
22
//
23
// Example:
24
// "/": regexp.MustCompile("((.*).js|(.*).css|(.*).ico)quot;)
25
// See `iris.MatchCommonAssets` too.
26
PushTargetsRegexp map[string]*regexp.Regexp
27
28
// Cache to enable in-memory cache and pre-compress files.
29
Cache DirCacheOptions
30
// When files should served under compression.
31
Compress bool
32
33
// List the files inside the current requested
34
// directory if `IndexName` not found.
35
ShowList bool
36
// If `ShowList` is true then this function will be used instead
37
// of the default one to show the list of files of
38
// a current requested directory(dir).
39
// See `DirListRich` package-level function too.
40
DirList DirListFunc
41
42
// Files downloaded and saved locally.
43
Attachments Attachments
44
45
// Optional validator that loops through each requested resource.
46
AssetValidator func(ctx *context.Context, name string) bool
47
}
Copied!

Quick Start

Let's say that you have an ./assets folder near to your executable and you want the files to be served through http://localhost:8080/static/**/* route.
1
app := iris.New()
2
3
app.HandleDir("/static", iris.Dir("./assets"))
4
5
app.Listen(":8080")
Copied!
Now, if you want to embed the static files to be lived inside the executable build in order to not depend on a system directory you can use a tool like go-bindata to convert the files into []byte inside your program. Let's take a quick tutorial on this and how Iris helps to serve those data.
Install go-bindata:
1
$ go get -u github.com/go-bindata/go-bindata/v3/go-bindata
Copied!
Navigate to your program directory, that the ./assets subdirectory exists and execute:
1
$ go-bindata -fs -prefix "assets" ./assets/...
Copied!
The above creates a generated go file which contains a AssetFile() functions that returns a compatible http.FileSystem you can give to Iris to serve the files.
1
// [app := iris.New...]
2
3
app.HandleDir("/static", AssetFile())
Copied!
Run your app:
1
$ go run .
Copied!
The HandleDir supports all the standards, including content-range, for both physical, embedded and cached directories.
However, if you just need a handler to work with, without register a route, you can use the iris.FileServer package-level function instead.
The FileServer function returns a Handler which serves files from a specific system directory, an embedded one or a memory-cached one.
1
iris.FileServer(fs http.FileSystem, options DirOptions)
Copied!
Usage
1
handler := iris.FileServer(iris.Dir("./assets"), iris.DirOptions {
2
ShowList: true, Compress: true, IndexName: "index.html",
3
})
Copied!

Example

Let's create an application that users can upload one or more files and list them.
Copy-paste the contents of main.go:
1
package main
2
3
import (
4
"crypto/md5"
5
"fmt"
6
"io"
7
"mime/multipart"
8
"os"
9
"strconv"
10
"strings"
11
"time"
12
13
"github.com/kataras/iris/v12"
14
)
15
16
func init() {
17
os.Mkdir("./uploads", 0700)
18
}
19
20
func main() {
21
app := iris.New()
22
app.RegisterView(iris.HTML("./views", ".html"))
23
// Serve assets (e.g. javascript, css).
24
app.HandleDir("/public", iris.Dir("./public"))
25
26
app.Get("/", index)
27
28
app.Get("/upload", uploadView)
29
app.Post("/upload", upload)
30
31
app.HandleDir("/files", iris.Dir("./uploads"), iris.DirOptions{
32
Compress: true,
33
ShowList: true,
34
})
35
36
app.Listen(":8080")
37
}
38
39
func index(ctx iris.Context) {
40
ctx.Redirect("/upload")
41
}
42
43
func uploadView(ctx iris.Context) {
44
now := time.Now().Unix()
45
h := md5.New()
46
io.WriteString(h, strconv.FormatInt(now, 10))
47
token := fmt.Sprintf("%x", h.Sum(nil))
48
49
ctx.View("upload.html", token)
50
}
51
52
const maxSize = 10 * iris.MB
53
54
func upload(ctx iris.Context) {
55
ctx.SetMaxRequestBodySize(maxSize)
56
57
_, _, err := ctx.UploadFormFiles("./uploads", beforeSave)
58
if err != nil {
59
ctx.StopWithError(iris.StatusPayloadTooRage, err)
60
return
61
}
62
63
ctx.Redirect("/files")
64
}
65
66
func beforeSave(ctx iris.Context, file *multipart.FileHeader) {
67
ip := ctx.RemoteAddr()
68
ip = strings.ReplaceAll(ip, ".", "_")
69
ip = strings.ReplaceAll(ip, ":", "_")
70
71
file.Filename = ip + "-" + file.Filename
72
}
Copied!
The ./views/upload.html is a simple html form, looks like that:
1
<!DOCTYPE html>
2
<html lang="en">
3
4
<head>
5
<meta charset="UTF-8">
6
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7
<title>Upload Files</title>
8
</head>
9
10
<body>
11
<form enctype="multipart/form-data" action="/upload" method="POST">
12
<input type="file" id="upload_files" name="upload_files" multiple />
13
<input type="hidden" name="token" value="{{.}}" />
14
15
<input type="button" value="Upload Using JS" onclick="uploadFiles()" />
16
<input type="submit" value="Upload by submiting the form" />
17
</form>
18
19
<script type="text/javascript">
20
function uploadFiles() {
21
let files = document.getElementById("upload_files").files;
22
let formData = new FormData();
23
for (var i = 0; i < files.length; i++) {
24
formData.append("files[]", files[i]);
25
}
26
27
fetch('/upload',
28
{
29
method: "POST",
30
body: formData
31
}).
32
then(data => window.location = "/files").
33
catch(e => window.alert("upload failed: file too large"));
34
}
35
</script>
36
</body>
37
38
</html>
Copied!
Last modified 1yr ago
Export as PDF
Copy link