-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patheager.go
More file actions
117 lines (96 loc) · 2.32 KB
/
Copy patheager.go
File metadata and controls
117 lines (96 loc) · 2.32 KB
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
package eager
import (
"fmt"
"os"
"reflect"
"time"
"log"
"sync"
)
//Enum the config type
const (
_ ConfigType = iota //int enum type
TOML //toml
)
//ConfigType config type constant int
type ConfigType int
// Config struct is details info
type Config struct {
Path string
MonitorTime time.Duration
modTime time.Time
storge interface{}
parseFunc func(path string, config interface{}) error
rwLock sync.RWMutex
}
// NewConfig method is return Config instance
func NewConfig(path string) *Config {
fileInfo, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
panic("file is not exist")
}
if fileInfo.IsDir() {
panic("is dir")
}
panic(fmt.Errorf("get file stat error: %s", err.Error()))
}
return &Config{Path: path, modTime: fileInfo.ModTime(), MonitorTime: time.Second * 3}
}
//Parse method load config,
//If config is not empty, the configuration is parsed into config
//If config is empty, it is parsed into config according to configType, You'll be able to use the get... method
func (c *Config) Parse(configType ConfigType, config interface{}) error {
var parser Parser
switch configType {
case TOML:
parser = &TOMLParser{}
}
if config != nil {
if reflect.ValueOf(config).Kind() != reflect.Ptr {
return ErrNotPtr
}
if err := parser.ParseConfig(c.Path, config); err != nil {
return err
}
c.storge, c.parseFunc = config, parser.ParseConfig
} else {
m := make(map[string]interface{})
if err := parser.ParseConfig(c.Path, &m); err != nil {
return err
}
c.storge, c.parseFunc = &m, parser.ParseConfig
}
//start goroutine to monitor change
go c.monitorChange()
return nil
}
//monitorChange monitor file Change
func (c *Config) monitorChange() {
ticker := time.NewTicker(c.MonitorTime)
for range ticker.C {
func() {
fileInfo, err := os.Stat(c.Path)
if err != nil {
if os.IsNotExist(err) {
log.Println(ErrNotExist)
}
if fileInfo.IsDir() {
log.Println(ErrNotFile)
}
log.Println("get file stat error: ", err)
return
}
if fileInfo.ModTime().Equal(c.modTime) {
return
}
c.rwLock.Lock()
defer c.rwLock.Unlock()
if err := c.parseFunc(c.Path, c.storge); err == nil {
c.modTime = fileInfo.ModTime()
} else {
log.Println("parse error: ", err.Error())
}
}()
}
}