-
Notifications
You must be signed in to change notification settings - Fork 0
/
static.go
95 lines (80 loc) · 1.81 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
package ela
import (
"net/http"
"os"
"path/filepath"
)
var (
staticDirectory = "static"
specialStatic []string
)
func init() {
staticDirectory = config.GetStringDefault("static", "path", "static")
}
func staticServ(uri string, ctx *Context) {
path := uri
stat, err := os.Stat(filepath.Join(staticDirectory, path))
if err != nil {
// 404
servError(ctx, "<h2>404, File N-ot Exist</h2>", 404, false)
return
}
if !stat.IsDir() {
// read file
servPath(path, ctx)
} else {
path = path + "/index.html"
servPath(path, ctx)
}
}
func servPath(path string, ctx *Context) {
writer := ctx.w
request := ctx.r
FileSystem := newStaticFileSystem(staticDirectory)
f, err := FileSystem.Open(path)
if err != nil {
// 404
servError(ctx, "<h2>404, File N*ot Exist</h2>", 404, false)
return
} else {
fi, err := f.Stat()
if err != nil {
// File exists but fail to open.
// 404
servError(ctx, "<h2>404, File N/ot Exist</h2>", 404, false)
return
}
http.ServeContent(writer, request, path, fi.ModTime(), f)
}
}
func staticExist(uri string) bool {
path := filepath.Join(staticDirectory, uri)
_, err := os.Stat(path)
if err != nil {
return false
} else {
return true
}
}
// add special static files into list
func addSpecialStatic(path string) {
specialStatic = append(specialStatic, path)
}
// staticFileSystem implements http.FileSystem interface.
type staticFileSystem struct {
dir *http.Dir
}
func newStaticFileSystem(directory string) staticFileSystem {
Root, err := os.Getwd()
if err != nil {
panic("error getting work directory: " + err.Error())
}
if !filepath.IsAbs(directory) {
directory = filepath.Join(Root, directory)
}
dir := http.Dir(directory)
return staticFileSystem{&dir}
}
func (fs staticFileSystem) Open(name string) (http.File, error) {
return fs.dir.Open(name)
}