-
Notifications
You must be signed in to change notification settings - Fork 0
/
static.go
58 lines (49 loc) · 1.16 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
package mano
import (
"errors"
"fmt"
"net/http"
"strings"
)
type StaticFileHandler struct {
app *Application
fileHandler http.Handler
prefix string
suffix []string
}
func (handler *StaticFileHandler) Init(app *Application) error {
handler.app = app
return nil
}
func (handler *StaticFileHandler) Handle(writer http.ResponseWriter, request *http.Request) (complated bool, err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New(fmt.Sprint(r))
}
}()
origin := request.URL
upath := request.URL.Path
//log.Debug("request url:%s\n", request.URL)
// 处理静态文件
if strings.HasPrefix(upath, handler.prefix) {
upath = upath[len(handler.prefix):]
if !strings.HasPrefix(upath, "/") {
upath = "/" + upath
}
request.URL.Path = upath
complated = true
handler.fileHandler.ServeHTTP(writer, request)
return
}
request.URL = origin
return false, err
}
func Static(root, prefix string, suffix ...string) *StaticFileHandler {
fileHandler := http.FileServer(http.Dir(root))
//TODO:处理路径及后缀
return &StaticFileHandler{
fileHandler: fileHandler,
prefix: prefix,
suffix: suffix,
}
}