/
static.go
105 lines (87 loc) · 2.14 KB
/
static.go
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package prago
import (
"bytes"
"embed"
"errors"
"io"
"io/fs"
"net/http"
"os"
"path"
)
var errFileNotFound = errors.New("requested file is folder")
//go:embed public
var staticAdminFS embed.FS
func (app *App) initStaticFilesHandler() {
app.staticFiles = staticFiles{}
app.AddStaticFiles(staticAdminFS, "public")
}
// AddStaticFiles add filesystem of public files and publish them in server's root
func (app *App) AddStaticFiles(f fs.FS, pathPrefix string) {
app.staticFiles.filesystems = append(app.staticFiles.filesystems, staticFS{
fs: f,
pathPrefix: pathPrefix,
})
}
// AddDevStaticFiles adds path for public files for development and publish them in server's root
func (app *App) AddDevStaticFiles(path string) {
app.staticFiles.devFilesystems = append(app.staticFiles.devFilesystems, path)
}
type staticFiles struct {
devFilesystems []string
filesystems []staticFS
}
type staticFS struct {
fs fs.FS
pathPrefix string
}
func (request Request) serveStatic() bool {
if request.app.developmentMode {
for _, v := range request.app.staticFiles.devFilesystems {
filesystem := os.DirFS(v)
filePath := path.Join("", request.r.URL.Path[1:])
err := request.serveStaticFile(filesystem, filePath)
if err == nil {
return true
}
}
}
for _, v := range request.app.staticFiles.filesystems {
filePath := path.Join(v.pathPrefix, request.r.URL.Path)
err := request.serveStaticFile(v.fs, filePath)
if err == nil {
return true
}
}
return false
}
func (request Request) serveStaticFile(filesystem fs.FS, name string) (err error) {
f, err := filesystem.Open(name)
if err != nil {
return
}
defer f.Close()
d, err := f.Stat()
if err != nil {
return errFileNotFound
}
if d.IsDir() {
f.Close()
f, err = filesystem.Open(name + "/index.html")
if err != nil {
return
}
d, err = f.Stat()
if err != nil {
return errFileNotFound
}
if d.IsDir() {
return errFileNotFound
}
}
b, _ := io.ReadAll(f)
reader := bytes.NewReader(b)
request.Response().Header().Add("Cache-Control", "max-age=604800")
http.ServeContent(request.w, request.r, d.Name(), d.ModTime(), reader)
return nil
}