-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocalHandler.go
102 lines (88 loc) · 2.14 KB
/
localHandler.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
93
94
95
96
97
98
99
100
101
102
package gogaecms
import (
"crypto/md5"
"encoding/csv"
"encoding/hex"
"html/template"
"io"
"net/http"
"os"
"path/filepath"
"io/ioutil"
"strings"
"mime"
)
type LocalHandler struct {
folder string
}
func NewLocalHandler(folder string) *LocalHandler {
return &LocalHandler{folder: folder}
}
func (h *LocalHandler) NewContext(_ *Request) Context {
return nil
}
func (h *LocalHandler) ServeStatic(req *Request) {
http.ServeFile(req.w, req.r, filepath.Join(h.folder, req.fileName))
}
func (h *LocalHandler) GetFromCache(_ *Request) *Content {
return nil
}
func (h *LocalHandler) Get(req *Request) *Content {
name := filepath.Join(h.folder, req.fileName)
bytes, err := ioutil.ReadFile(name)
if err != nil {
return nil
}
md5Sum := md5.Sum(bytes)
etag := hex.EncodeToString(md5Sum[:])
content := Content{Data: bytes, ETag: etag}
return &content
}
func (h *LocalHandler) PutToCache(_ *Request, _ *Content) {
}
func (h *LocalHandler) SendContent(req *Request, content *Content) {
mimeType := mime.TypeByExtension(req.fileName[strings.LastIndex(req.fileName, "."):])
req.w.Header().Add("Cache-Control", "public")
req.w.Header().Add("ETag", content.ETag)
req.w.Header().Add("Content-Type", mimeType)
req.w.Write(content.Data)
}
func (h *LocalHandler) LoadDatas(_ *Request) (DataEntities, error) {
files, err := filepath.Glob("site/data/*")
if err != nil {
return nil, err
}
result := make(DataEntities)
for n := range files {
file, err := os.Open(files[n])
if err != nil {
return nil, err
}
defer file.Close()
records, err := loadCSV(file)
if err != nil {
return nil, err
}
result["items"] = records
}
return result, nil
}
func loadCSV(file io.Reader) ([]DataRecord, error) {
reader := csv.NewReader(file)
var result []DataRecord
for {
record, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
result = append(result, record)
}
return result, nil
}
func (h *LocalHandler) LoadTemplates(_ *Request,root *template.Template) (*template.Template, error) {
pattern := filepath.Join(h.folder, "*.html")
template := template.Must(root.ParseGlob(pattern))
return template, nil
}