/
static.go
62 lines (56 loc) · 1.37 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
package api
import (
"bytes"
"fmt"
"net/http"
"path/filepath"
"strings"
"time"
"github.com/keydotcat/keycatd/static"
)
//HACK: html/template removes the html comments and since we only require the csrf.. :P
type StaticHandler struct {
Dir string
IndexFile string
cacheStatic bool
}
func NewStaticHandler() *StaticHandler {
return &StaticHandler{
Dir: "web",
IndexFile: "index.html",
cacheStatic: true,
}
}
func (s *StaticHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "HEAD" {
http.NotFound(rw, r)
return
}
file := r.URL.Path
if strings.Index(file, "/api/") == 0 || strings.Index(file, "/oa/") == 0 {
http.NotFound(rw, r)
return
}
file = strings.TrimLeft(file, "/")
cacheResource := s.cacheStatic
if len(file) == 0 || file == s.IndexFile || len(filepath.Ext(file)) == 0 {
file = s.IndexFile
cacheResource = false
}
filePath := fmt.Sprintf("%s/%s", s.Dir, file)
finfo, err := static.AssetInfo(filePath)
if err != nil {
http.NotFound(rw, r)
return
}
data, err := static.Asset(filePath)
if err != nil {
http.NotFound(rw, r)
return
}
if cacheResource {
rw.Header().Add("Cache-Control", "public, max-age=31536000")
rw.Header().Add("Expires", time.Now().Add(30*24*time.Hour).Format(time.RFC1123))
}
http.ServeContent(rw, r, file, finfo.ModTime(), bytes.NewReader(data))
}