forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
static_handler.go
80 lines (71 loc) · 1.72 KB
/
static_handler.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
package uadmin
import (
"fmt"
"net/http"
"os"
"path"
"strings"
"time"
)
func containsDotDot(v string) bool {
if !strings.Contains(v, "..") {
return false
}
for _, ent := range strings.FieldsFunc(v, func(r rune) bool { return r == '/' || r == '\\' }) {
if ent == ".." {
return true
}
}
return false
}
// StaticHandler is a function that serves static files
func StaticHandler(w http.ResponseWriter, r *http.Request) {
if containsDotDot(r.URL.Path) {
w.WriteHeader(404)
return
}
var modTime time.Time
ab := false
var midnightDelta int
for k := range staticABTests {
if k == r.URL.Path && len(staticABTests[k]) != 0 {
index := getABT(r) % len(staticABTests[k])
r.URL.Path = staticABTests[k][index].v
// Calculate number of seconds until midnight if no calculated yet
if midnightDelta == 0 {
midnight := time.Now()
midnight = time.Date(midnight.Year(), midnight.Month(), midnight.Day(), 0, 0, 0, 0, midnight.Location())
midnightDelta = int(time.Until(midnight).Seconds())
}
// Add a header to expire the satic content at midnigh
w.Header().Add("Cache-Control", "private, max-age="+fmt.Sprint(midnightDelta))
ab = true
go func(index int) {
abTestsMutex.Lock()
t := staticABTests[k]
t[index].imp++
staticABTests[k] = t
abTestsMutex.Unlock()
}(index)
break
}
}
fName := path.Clean(r.URL.Path)
f, err := os.Open("." + fName)
if err != nil {
w.WriteHeader(404)
return
}
if !ab {
stat, err := os.Stat("." + fName)
if err != nil || stat.IsDir() {
w.WriteHeader(404)
return
}
modTime = stat.ModTime()
w.Header().Add("Cache-Control", "private, max-age=3600")
} else {
modTime = time.Now()
}
http.ServeContent(w, r, "."+fName, modTime, f)
}