aboutsummaryrefslogtreecommitdiff
path: root/pkg/ext/fileserver.go
blob: ee4a80b1127e7f7cb6d5d1124931b7f2d65b7b9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package ext

import (
	"io/fs"
	"mime"
	"path/filepath"

	"github.com/valyala/fasthttp"
)

type FileSystem interface {
	Open(name string) (fs.File, error)
}

// This is a VERY simple file server. It does not take a lot into consideration
// and it should only be used to return small predictable files, like in the
// static folder.
func FileServer(rootFS FileSystem, rootPath string) fasthttp.RequestHandler {
	return func(ctx *fasthttp.RequestCtx) {
		path := ctx.UserValue("filepath").(string)

		f, err := rootFS.Open(rootPath + path)
		if err != nil {
			InternalServerError(ctx, err)
			return
		}
		defer f.Close()

		m := mime.TypeByExtension(filepath.Ext(path))
		ctx.SetContentType(m)
		ctx.SetBodyStream(f, -1)
	}
}