-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStatic.go
More file actions
43 lines (40 loc) · 985 Bytes
/
Copy pathStatic.go
File metadata and controls
43 lines (40 loc) · 985 Bytes
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
package rest
import (
"io"
"os"
"path"
"time"
)
//static middleaware configuration
type StaticConf struct {
CacheControl string
}
//rest static file server middleware
func Static(dir string, conf ...StaticConf) func(request Request, response Response, next func()) {
stat, e := os.Stat(dir)
if nil != e {
panic(e)
}
if !stat.IsDir() {
panic(&RestError{Reason: dir + " directory not exists!"})
}
return func(request Request, response Response, next func()) {
file := path.Join(dir, request.Path)
fileInfo, e := os.Stat(file)
if nil != e || fileInfo.IsDir() {
next()
return
}
since := request.Get("If-Modified-Since")
if 0 != len(since) {
sinceTime, e := time.Parse(GMT_FORMAT, since)
if nil == e && (sinceTime.Unix()-fileInfo.ModTime().Unix() >= 0) {
response.Status(304)
return
}
}
response.Set("Last-Modified", fileInfo.ModTime().UTC().Format(GMT_FORMAT))
openedFile, e := os.Open(file)
io.Copy(&response, openedFile)
}
}