-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.go
96 lines (86 loc) · 2.34 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
package ngin
import (
"html/template"
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
"github.com/gin-contrib/multitemplate"
"github.com/gin-gonic/gin"
)
// LoadTemplateFunc 加载模板函数类
type LoadTemplateFunc func(templatesDir string, funcMap template.FuncMap, templates ...string) multitemplate.Render
// EngineTemplate gin引擎模板
type EngineTemplate struct {
templatesDir string
templates []string
engine *gin.Engine
watcher *fsnotify.Watcher
Errors <-chan error
loadTemplateFunc LoadTemplateFunc
funcMap template.FuncMap
}
// NewEngineTemplate 创建一个gin引擎模板
func NewEngineTemplate(templateDir string, engine *gin.Engine, tmplFunc LoadTemplateFunc, funcMap template.FuncMap, templates ...string) (*EngineTemplate, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
return &EngineTemplate{
templatesDir: templateDir,
templates: templates,
engine: engine,
loadTemplateFunc: tmplFunc,
watcher: watcher,
Errors: make(<-chan error),
funcMap: funcMap,
}, nil
}
// Watching 监听模板文件夹中是否有变动
func (tmpl *EngineTemplate) Watching() error {
tmpl.Errors = tmpl.watcher.Errors
go func() {
for {
event := <-tmpl.watcher.Events
loadFlag := true
switch event.Op {
case fsnotify.Create:
fileInfo, err := os.Stat(event.Name)
if err == nil && fileInfo.IsDir() {
tmpl.watcher.Add(event.Name)
}
case fsnotify.Remove, fsnotify.Rename:
fileInfo, err := os.Stat(event.Name)
if err == nil && fileInfo.IsDir() {
tmpl.watcher.Remove(event.Name)
}
case fsnotify.Chmod:
loadFlag = false
}
if loadFlag {
tmpl.engine.HTMLRender = tmpl.LoadTemplate()
}
}
}()
//遍历目录下的所有子目录
err := filepath.Walk(tmpl.templatesDir, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
err := tmpl.watcher.Add(path)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
return nil
}
// Close 关闭
func (tmpl *EngineTemplate) Close() error {
return tmpl.watcher.Close()
}
// LoadTemplate 加载模板
func (tmpl *EngineTemplate) LoadTemplate() multitemplate.Render {
return tmpl.loadTemplateFunc(tmpl.templatesDir, tmpl.funcMap, tmpl.templates...)
}