-
Notifications
You must be signed in to change notification settings - Fork 0
/
static.go
75 lines (64 loc) · 1.61 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
package static
import (
"errors"
"os"
"github.com/valyala/fasthttp"
)
// DefaultFS the defalut config of fasthttp.FS
var DefaultFS = &fasthttp.FS{
Compress: true,
IndexNames: []string{"index.html"},
Root: ".",
AcceptByteRange: true,
}
// New accepts fs which is a *fasthttp.FS pointer.
//
// if the http request method is not 'GET' or 'HEAD', the static will call next(nil)
//
// if the http request file does not exist or the directory does not have the IndexNames file.
// the static will call next(nil)
//
// or, fasthttp.FS will handle the request file or the IndexNames file in the request directory
func New(fs *fasthttp.FS) func(ctx *fasthttp.RequestCtx, next func(error)) {
staticHandler := fs.NewRequestHandler()
return func(ctx *fasthttp.RequestCtx, next func(error)) {
m := string(ctx.Method())
if m != "GET" && m != "HEAD" {
next(nil)
return
}
path := string(ctx.Path())
fileInfo, err := os.Stat(fs.Root + path)
// if err != nil && os.IsNotExist(err) {
if err != nil {
next(nil)
return
}
// An exist file
// fasthttp.FS handle it
if !fileInfo.IsDir() {
staticHandler(ctx)
return
}
if len(fs.IndexNames) == 0 {
next(nil)
return
}
errPath := filterPath(fs.Root+path+"/", fs.IndexNames, next)
if errPath != nil {
next(nil)
return
}
// An exist directory has IndexNames file
staticHandler(ctx)
}
}
func filterPath(path string, index []string, next func(error)) error {
for _, v := range index {
_, err := os.Stat(path + v)
if err == nil {
return nil
}
}
return errors.New("Not found index page in directory: " + path)
}