forked from devfeel/dotweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
98 lines (87 loc) · 2.32 KB
/
plugin.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
package dotweb
import (
"fmt"
"github.com/devfeel/dotweb/config"
"os"
"path/filepath"
"time"
)
// Plugin a interface for app's global plugin
type Plugin interface {
Name() string
Run() error
IsValidate() bool
}
// NewDefaultNotifyPlugin return new NotifyPlugin with default config
func NewDefaultNotifyPlugin(app *DotWeb) *NotifyPlugin {
p := new(NotifyPlugin)
p.app = app
p.LoopTime = notifyPlugin_LoopTime
p.Root = app.Config.ConfigFilePath
p.suffix = make(map[string]bool)
p.ModTimes = make(map[string]time.Time)
return p
}
// NewNotifyPlugin return new NotifyPlugin with fileRoot & loopTime & suffix
// if suffix is nil or suffix[0] == "*", will visit all files in fileRoot
/*func NewNotifyPlugin(app *DotWeb, fileRoot string, loopTime int, suffix []string) *NotifyPlugin{
p := new(NotifyPlugin)
p.app = app
p.LoopTime = loopTime
p.Root = fileRoot
Suffix := make(map[string]bool)
if len(suffix) > 0 && suffix[0] != "*" {
for _, v := range suffix {
Suffix[v] = true
}
}
p.suffix = Suffix
p.ModTimes = make(map[string]time.Time)
return p
}*/
const notifyPlugin_LoopTime = 500 //ms
type NotifyPlugin struct {
app *DotWeb
Root string
suffix map[string]bool
LoopTime int
ModTimes map[string]time.Time
}
func (p *NotifyPlugin) Name() string {
return "NotifyPlugin"
}
func (p *NotifyPlugin) IsValidate() bool {
return true
}
func (p *NotifyPlugin) Run() error {
return p.start()
}
func (p *NotifyPlugin) visit(path string, fileinfo os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("访问文件失败%s", err)
}
ext := filepath.Ext(path)
if !fileinfo.IsDir() && (p.suffix[ext] || len(p.suffix) == 0) {
modTime := fileinfo.ModTime()
if oldModTime, ok := p.ModTimes[path]; !ok {
p.ModTimes[path] = modTime
} else {
if oldModTime.Before(modTime) {
p.app.Logger().Info("NotifyPlugin Reload "+path, LogTarget_HttpServer)
appConfig, err := config.InitConfig(p.app.Config.ConfigFilePath, p.app.Config.ConfigType)
if err != nil {
p.app.Logger().Error("NotifyPlugin Reload "+path+" error => "+fmt.Sprint(err), LogTarget_HttpServer)
}
p.app.ReSetConfig(appConfig)
p.ModTimes[path] = modTime
}
}
}
return nil
}
func (p *NotifyPlugin) start() error {
for {
filepath.Walk(p.Root, p.visit)
time.Sleep(time.Duration(p.LoopTime) * time.Millisecond)
}
}