-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathtplhandler.go
73 lines (61 loc) · 1.75 KB
/
tplhandler.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
package server
import (
"bytes"
"io"
"net/http"
"os"
"path/filepath"
"sync"
"text/template"
"time"
"go.uber.org/zap"
)
type TemplateArguments struct {
GoogleTagID string
}
type TemplateFileServer struct {
log *zap.Logger
filePath string
templateVars TemplateArguments
once *sync.Once
buffer io.ReadSeeker
modTime time.Time
}
// NewTemplateFileServer returns handler which compiles and serves HTML page template.
func NewTemplateFileServer(logger *zap.Logger, filePath string, tplVars TemplateArguments) *TemplateFileServer {
return &TemplateFileServer{
log: logger,
once: new(sync.Once),
filePath: filePath,
templateVars: tplVars,
}
}
func (fs *TemplateFileServer) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
fs.once.Do(fs.precompileTemplate)
if fs.buffer == nil {
http.ServeFile(rw, r, fs.filePath)
return
}
http.ServeContent(rw, r, fs.filePath, fs.modTime, fs.buffer)
}
func (fs *TemplateFileServer) precompileTemplate() {
stat, err := os.Stat(fs.filePath)
if err != nil {
fs.log.Error("failed to read template file", zap.Error(err), zap.String("filePath", fs.filePath))
return
}
tpl, err := template.New(filepath.Base(fs.filePath)).ParseFiles(fs.filePath)
if err != nil {
fs.log.Error("failed to parse page template", zap.Error(err), zap.String("filePath", fs.filePath))
return
}
buff := new(bytes.Buffer)
buff.Grow(int(stat.Size()))
if err := tpl.Execute(buff, fs.templateVars); err != nil {
fs.log.Error("failed to execute page template", zap.Error(err), zap.String("filePath", fs.filePath))
return
}
fs.log.Info("successfully compiled page template", zap.String("filePath", fs.filePath))
fs.buffer = bytes.NewReader(buff.Bytes())
fs.modTime = time.Now()
}