-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtemplate.go
234 lines (180 loc) · 5.02 KB
/
template.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// Copyright 2015 Eryx <evorui at gmail dot com>, All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package httpsrv
import (
"bytes"
"errors"
"fmt"
"html/template"
"io"
"net/http"
"path"
"strings"
"sync"
"github.com/hooto/httpsrv/internal/lru"
)
// This object handles loading and parsing of templates.
// Everything below the application's views directory is treated as a template.
type TemplateLoader struct {
mu sync.RWMutex
// Map from template name to the path from whence it was loaded.
templatePaths map[string]string
// This is the set of all templates under views
templateSets map[string]*template.Template
templateCache *lru.Cache
}
func (it *TemplateLoader) Clean(modUrlBase string) {
it.mu.Lock()
defer it.mu.Unlock()
if _, ok := it.templateSets[modUrlBase]; ok {
delete(it.templateSets, modUrlBase)
}
for k := range it.templatePaths {
if strings.HasPrefix(k, modUrlBase+".") {
delete(it.templatePaths, k)
}
}
}
func (it *TemplateLoader) Set(modUrlBase string, viewpaths []string, viewfss []http.FileSystem) {
it.mu.Lock()
defer it.mu.Unlock()
loaderTemplateSet, ok := it.templateSets[modUrlBase]
if ok {
return
}
addTemplate := func(templateFile, fileStr string) error {
var (
templateName = strings.Trim(templateFile, "/")
templateNameL = strings.ToLower(templateName)
)
if _, ok := it.templatePaths[modUrlBase+"."+templateNameL]; ok {
return nil
}
var err error
if loaderTemplateSet == nil {
func() {
defer func() {
if e := recover(); e != nil {
err = errors.New("Panic (Template Loader)")
}
}()
loaderTemplateSet = template.New(templateName).Funcs(TemplateFuncs)
if _, err = loaderTemplateSet.Parse(fileStr); err == nil {
it.templateSets[modUrlBase] = loaderTemplateSet
}
}()
} else {
_, err = loaderTemplateSet.New(templateName).Parse(fileStr)
}
if err == nil {
if templateNameL != templateName {
loaderTemplateSet.New(templateNameL).Parse(fileStr)
}
it.templatePaths[modUrlBase+"."+templateNameL] = templateFile
defaultLogger.Infof("httpsrv: module %s, template %s added", modUrlBase, templateFile)
} else {
defaultLogger.Warnf("httpsrv: module %s, template %s parse err %s", modUrlBase, templateFile, err.Error())
}
return err
}
var hfsWalk func(fs http.FileSystem, dir string) error
hfsWalk = func(fs http.FileSystem, dir string) error {
fp, err := fs.Open(dir)
if err != nil {
return err
}
defer fp.Close()
st, err := fp.Stat()
if err != nil {
return err
}
if !st.IsDir() {
if strings.HasSuffix(dir, ".tpl") ||
strings.HasSuffix(dir, ".html") {
var buf bytes.Buffer
if _, err = io.Copy(&buf, fp); err != nil {
return err
}
addTemplate(dir, buf.String())
}
return nil
}
nodes, err := fp.Readdir(-1)
if err != nil {
return err
}
for _, n := range nodes {
if n.Name() == "." || n.Name() == ".." {
continue
}
if err = hfsWalk(fs, path.Join(dir, n.Name())); err != nil {
return err
}
}
return nil
}
for _, baseDir := range viewpaths {
hfsWalk(http.Dir(baseDir), "/")
}
for _, fs := range viewfss {
hfsWalk(fs, "/")
}
}
func (it *TemplateLoader) Render(wr io.Writer, modUrlBase, tplPath string, arg interface{}) error {
defer func() {
if err := recover(); err != nil {
defaultLogger.Debugf("httpsrv: template (%s/%s) render err %v", modUrlBase, tplPath, err)
}
}()
// defaultLogger.Infof("httpsrv: template (%s/%s) render", modUrlBase, tplPath)
it.mu.RLock()
tplSet, ok := it.templateSets[modUrlBase]
it.mu.RUnlock()
if !ok || tplSet == nil {
return fmt.Errorf("module %s not found", modUrlBase)
}
// return tplSet.ExecuteTemplate(wr, tplPath, arg)
tpl := tplSet.Lookup(tplPath)
if tpl == nil {
if tplPathl := strings.ToLower(tplPath); tplPathl != tplPath {
tpl = tplSet.Lookup(tplPathl)
}
if tpl == nil {
return fmt.Errorf("template %s/%s not found", modUrlBase, tplPath)
}
}
return tpl.Execute(wr, arg)
}
func (it *TemplateLoader) rawRender(wr io.Writer, txt string, arg interface{}) error {
defer func() {
if err := recover(); err != nil {
defaultLogger.Debugf("httpsrv: raw-render err %v", err)
}
}()
var (
hkey = crc64Checksum([]byte(txt))
tpl *template.Template
)
if itpl, ok := it.templateCache.Get(hkey); !ok {
tpl, err := template.New("raw").Parse(txt)
if err != nil {
return err
}
tpl = tpl.Funcs(TemplateFuncs)
it.templateCache.Add(hkey, tpl)
} else {
tpl = itpl.(*template.Template)
}
return tpl.Execute(wr, arg)
}