github.com/zooyer/miskit@v1.0.71/conf/conf.go (about) 1 package conf 2 3 import ( 4 "fmt" 5 "strings" 6 "sync" 7 "time" 8 9 "github.com/spf13/viper" 10 ) 11 12 type Conf struct { 13 mutex sync.Mutex 14 viper *viper.Viper 15 ticker *time.Ticker 16 interval time.Duration 17 addr map[string]interface{} 18 } 19 20 func New(interval time.Duration) *Conf { 21 var conf Conf 22 conf.interval = interval 23 conf.viper = viper.New() 24 conf.addr = make(map[string]interface{}) 25 26 if interval > 0 { 27 conf.ticker = time.NewTicker(interval) 28 go conf.reload() 29 } 30 31 return &conf 32 } 33 34 func (c *Conf) toValue() { 35 c.mutex.Lock() 36 defer c.mutex.Unlock() 37 for key, addr := range c.addr { 38 _ = c.viper.UnmarshalKey(key, addr) 39 } 40 } 41 42 func (c *Conf) reload() { 43 for range c.ticker.C { 44 c.toValue() 45 } 46 } 47 48 func (c *Conf) key(key ...interface{}) string { 49 var keys = make([]string, 0, len(key)) 50 for _, key := range key { 51 keys = append(keys, fmt.Sprint(key)) 52 } 53 return strings.Join(keys, ".") 54 } 55 56 func (c *Conf) Stop() { 57 c.mutex.Lock() 58 defer c.mutex.Unlock() 59 if c.ticker != nil { 60 c.ticker.Stop() 61 } 62 } 63 64 func (c *Conf) Bind(key string, v interface{}) (err error) { 65 if err := c.viper.UnmarshalKey(key, v); err != nil { 66 return err 67 } 68 69 c.mutex.Lock() 70 defer c.mutex.Unlock() 71 72 if c.interval > 0 { 73 c.addr[key] = v 74 } 75 76 return 77 } 78 79 func (c *Conf) Init(filename string) (err error) { 80 c.viper.SetConfigFile(filename) 81 if c.interval > 0 { 82 c.viper.WatchConfig() 83 } 84 if err = c.viper.ReadInConfig(); err != nil { 85 return 86 } 87 return 88 }