forked from davyxu/cellnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
92 lines (71 loc) · 1.73 KB
/
file.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
package http
import (
"net/http"
"net/url"
"path"
"path/filepath"
"strings"
)
func (self *httpAcceptor) SetFileServe(dir string, root string) {
self.httpDir = dir
self.httpRoot = root
}
func (self *httpAcceptor) GetDir() http.Dir {
if filepath.IsAbs(self.httpDir) {
return http.Dir(self.httpDir)
} else {
return http.Dir(filepath.Join(self.httpRoot, self.httpDir))
}
//workDir, _ := os.Getwd()
//log.Debugf("Http serve file: %s (%s)", self.dir, workDir)
}
func (self *httpAcceptor) ServeFile(res http.ResponseWriter, req *http.Request, dir http.Dir) (error, bool) {
if req.Method != "GET" && req.Method != "HEAD" {
return nil, false
}
file := req.URL.Path
f, err := dir.Open(file)
if err != nil {
if err != nil {
return errNotFound, false
}
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return errNotFound, false
}
// try to serve index file
if fi.IsDir() {
// redirect if missing trailing slash
if !strings.HasSuffix(req.URL.Path, "/") {
dest := url.URL{
Path: req.URL.Path + "/",
RawQuery: req.URL.RawQuery,
Fragment: req.URL.Fragment,
}
http.Redirect(res, req, dest.String(), http.StatusFound)
return nil, false
}
file = path.Join(file, "index.html")
f, err = dir.Open(file)
if err != nil {
return errNotFound, false
}
defer f.Close()
fi, err = f.Stat()
if err != nil || fi.IsDir() {
return errNotFound, false
}
}
http.ServeContent(res, req, file, fi.ModTime(), f)
return nil, true
}
func (self *httpAcceptor) ServeFileWithDir(res http.ResponseWriter, req *http.Request) (msg interface{}, err error, handled bool) {
dir := self.GetDir()
if dir == "" {
return nil, errNotFound, false
}
err, handled = self.ServeFile(res, req, dir)
return
}