-
Notifications
You must be signed in to change notification settings - Fork 0
/
go_engine.go
267 lines (224 loc) · 7.34 KB
/
go_engine.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// go-aah/view source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package view
import (
"errors"
"fmt"
"html/template"
"io/ioutil"
"path/filepath"
"strings"
"aahframework.org/config.v0"
"aahframework.org/essentials.v0"
"aahframework.org/log.v0"
)
const noLayout = "nolayout"
// GoViewEngine implements the partial inheritance support with Go templates.
type GoViewEngine struct {
cfg *config.Config
baseDir string
layouts map[string]*Templates
viewFileExt string
caseSensitive bool
isDefaultLayoutEnabled bool
delimiters []string
antiCSRFField string
antiCSRFInserter *strings.Replacer
}
// Init method initialize a template engine with given aah application config
// and application views base path.
func (ge *GoViewEngine) Init(appCfg *config.Config, baseDir string) error {
if !ess.IsFileExists(baseDir) {
return fmt.Errorf("goviewengine: views base dir is not exists: %s", baseDir)
}
// Add template func
AddTemplateFunc(template.FuncMap{
"safeHTML": tmplSafeHTML,
"import": tmplImport,
})
// initialize common templates
if err := commonTemplate.Init(appCfg, baseDir); err != nil {
return err
}
ge.cfg = appCfg
ge.baseDir = baseDir
ge.layouts = make(map[string]*Templates)
ge.viewFileExt = ge.cfg.StringDefault("view.ext", ".html")
ge.caseSensitive = ge.cfg.BoolDefault("view.case_sensitive", false)
ge.isDefaultLayoutEnabled = ge.cfg.BoolDefault("view.default_layout", true)
ge.delimiters = strings.Split(ge.cfg.StringDefault("view.delimiters", "{{.}}"), ".")
if len(ge.delimiters) != 2 || ess.IsStrEmpty(ge.delimiters[0]) || ess.IsStrEmpty(ge.delimiters[1]) {
return fmt.Errorf("goviewengine: config 'view.delimiters' value is invalid")
}
// anti CSRF
ge.antiCSRFField = ` <input type="hidden" name="anti_csrf_token" value="{{ anitcsrftoken . }}">
</form>`
ge.antiCSRFField = strings.Replace(ge.antiCSRFField, "{{", ge.delimiters[0], -1)
ge.antiCSRFField = strings.Replace(ge.antiCSRFField, "}}", ge.delimiters[1], -1)
ge.antiCSRFInserter = strings.NewReplacer("</form>", ge.antiCSRFField)
layoutsBaseDir := filepath.Join(ge.baseDir, "layouts")
if !ess.IsFileExists(layoutsBaseDir) {
return fmt.Errorf("goviewengine: layouts base dir is not exists: %s", layoutsBaseDir)
}
pagesBaseDir := filepath.Join(ge.baseDir, "pages")
if !ess.IsFileExists(pagesBaseDir) {
return fmt.Errorf("goviewengine: pages base dir is not exists: %s", pagesBaseDir)
}
layouts, err := filepath.Glob(filepath.Join(layoutsBaseDir, "*"+ge.viewFileExt))
if err != nil {
return err
}
pageDirs, err := ess.DirsPath(pagesBaseDir, true)
if err != nil {
return err
}
if err = ge.processLayoutTemplates(layouts, pageDirs); err != nil {
return err
}
if !ge.isDefaultLayoutEnabled {
if err = ge.processNolayoutTemplates(pageDirs); err != nil {
return err
}
}
errorPagesDir := filepath.Join(ge.baseDir, "errors")
if ess.IsFileExists(errorPagesDir) {
if err = ge.processNolayoutTemplates([]string{errorPagesDir}); err != nil {
return err
}
}
return nil
}
// Get method returns the template based given name if found, otherwise nil.
func (ge *GoViewEngine) Get(layout, path, tmplName string) (*template.Template, error) {
if ess.IsStrEmpty(layout) {
layout = noLayout
}
if l, found := ge.layouts[layout]; found {
key := parseKey("", filepath.Join(path, tmplName))
if layout == noLayout {
key = noLayout + key
}
if ge.caseSensitive {
if t, found := l.Template[key]; found {
return t, nil
}
} else {
if t, found := l.TemplateLower[strings.ToLower(key)]; found {
return t, nil
}
}
}
return nil, ErrTemplateNotFound
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// GoViewEngine unexported methods
//___________________________________
func (ge *GoViewEngine) processLayoutTemplates(layouts, dirs []string) error {
var errs []error
for _, layout := range layouts {
lTemplate := &Templates{
Template: make(map[string]*template.Template),
TemplateLower: make(map[string]*template.Template),
}
for _, dir := range dirs {
files, err := filepath.Glob(filepath.Join(dir, "*"+ge.viewFileExt))
if err != nil {
errs = append(errs, err)
continue
}
for _, file := range files {
tfiles := []string{file, layout}
tmplKey := parseKey(ge.baseDir, file)
tmpl := template.New(tmplKey).Funcs(TemplateFuncMap)
tmpl.Delims(ge.delimiters[0], ge.delimiters[1])
tmplfiles := ge.processAntiCSRFField(tfiles...)
log.Tracef("Parsing files [%s]: %s", tmplKey, ge.trimAppBaseDir(tfiles...))
if tmpl, err = tmpl.ParseFiles(tmplfiles...); err != nil {
errs = append(errs, err)
continue
}
lTemplate.Template[tmplKey] = tmpl
lTemplate.TemplateLower[strings.ToLower(tmplKey)] = tmpl
}
}
ge.layouts[strings.ToLower(filepath.Base(layout))] = lTemplate
}
return handleParseError(errs)
}
func (ge *GoViewEngine) processNolayoutTemplates(dirs []string) error {
if _, found := ge.layouts[noLayout]; !found {
ge.layouts[noLayout] = &Templates{
Template: make(map[string]*template.Template),
TemplateLower: make(map[string]*template.Template),
}
}
var errs []error
prefix := strings.TrimSuffix(ge.baseDir, "views")
for _, dir := range dirs {
files, err := filepath.Glob(filepath.Join(dir, "*"+ge.viewFileExt))
if err != nil {
errs = append(errs, err)
continue
}
for _, file := range files {
tmplKey := parseKey(ge.baseDir, file)
tmpl := template.New(tmplKey).Funcs(TemplateFuncMap)
tmpl.Delims(ge.delimiters[0], ge.delimiters[1])
fileBytes, _ := ioutil.ReadFile(file)
fileContent := ge.antiCSRFInserter.Replace(string(fileBytes))
log.Tracef("Parsing file [%s]: %s", tmplKey, trimPathPrefix(file, prefix))
if tmpl, err = tmpl.Parse(fileContent); err != nil {
errs = append(errs, err)
continue
}
ge.layouts[noLayout].Template[noLayout+tmplKey] = tmpl
ge.layouts[noLayout].TemplateLower[strings.ToLower(noLayout+tmplKey)] = tmpl
}
}
return handleParseError(errs)
}
func (ge *GoViewEngine) trimAppBaseDir(files ...string) string {
var fs []string
prefix := strings.TrimSuffix(ge.baseDir, "views")
for _, f := range files {
fs = append(fs, trimPathPrefix(f, prefix))
}
return strings.Join(fs, ", ")
}
func (ge *GoViewEngine) processAntiCSRFField(filenames ...string) []string {
var files []string
tmpDir, _ := ioutil.TempDir("", "anti_csrf")
for _, f := range filenames {
fileBytes, err := ioutil.ReadFile(f)
if err != nil {
files = append(files, f)
continue
}
file := string(fileBytes)
rfile := ge.trimAppBaseDir(f)
if strings.Contains(file, "</form>") {
log.Tracef("Adding Anti-CSRF field into %s", rfile)
file = ge.antiCSRFInserter.Replace(file)
fpath := filepath.Join(tmpDir, rfile)
_ = ess.MkDirAll(filepath.Dir(fpath), 0755)
_ = ioutil.WriteFile(fpath, []byte(file), 0755)
files = append(files, fpath)
continue
}
files = append(files, f)
}
return files
}
func handleParseError(errs []error) error {
if len(errs) > 0 {
for _, e := range errs {
log.Error(e)
}
return errors.New("goviewengine: error processing templates, check the log")
}
return nil
}
func init() {
_ = AddEngine("go", &GoViewEngine{})
}