Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ReadConfig ¶
func UnmarshalConfig ¶
func WatchRemoteConfig ¶
func WatchRemoteConfig(opt *RemoteConfigOption) (<-chan struct{}, error)
Types ¶
type RemoteConfigOption ¶
type RemoteConfigOption struct {
// Etcd | Consul
Provider RemoteProvider `json:"provider"`
Endpoint string `json:"endpoint"`
// Path: config store path.
Path string `json:"path"`
// json | yaml
ConfigType string `json:"config_type"`
}
type RemoteProvider ¶
type RemoteProvider string
const ( Etcd RemoteProvider = "etcd" Consul RemoteProvider = "consul" )
type VConfig ¶
type VConfig struct {
// contains filtered or unexported fields
}
func NewVConfig ¶
func NewVConfig() *VConfig
func (*VConfig) ReadConfig ¶
ReadConfig read config into VConfig. Support config file format: json|yaml cfgFile: config file path, support file ext .json | .yaml
func (*VConfig) UnmarshalConfig ¶
UnmarshalConfig read config file into VConfig then decode it to struct.
func (*VConfig) WatchRemoteConfig ¶
func (vc *VConfig) WatchRemoteConfig(opt *RemoteConfigOption) (<-chan struct{}, error)
WatchRemoteConfig update config from remote provider for every 5 seconds. Return update signal channel or error. Example: ch, err := vc.WatchRemoteConfig(opt)
for sig := range ch {
vc.Unmarshal(dest)
}
Example ¶
package main
import (
"encoding/json"
"io/ioutil"
"log"
"os"
"fmt"
"github.com/RivenZoo/vcfg"
)
const testConfigFile = "cfg.json"
type testConfig struct {
Address string
Port int
}
func initTestConfig() (clean func(), err error) {
cfg := &testConfig{
"localhost",
80,
}
var data []byte
data, err = json.Marshal(cfg)
if err != nil {
return
}
err = ioutil.WriteFile(testConfigFile, data, 0644)
if err != nil {
return
}
clean = func() {
os.Remove(testConfigFile)
}
return
}
func main() {
clean, err := initTestConfig()
if err != nil {
log.Panicf("initTestConfig error: %v", err)
}
defer clean()
testCfg := &testConfig{}
cfg := vcfg.NewVConfig()
ch, err := cfg.WatchRemoteConfig(&vcfg.RemoteConfigOption{
Provider: vcfg.Consul,
Endpoint: "127.0.0.1:8500",
Path: "my_config_path",
ConfigType: "json",
})
if err != nil {
log.Panicf("WatchRemoteConfig error: %v", err)
}
fmt.Println("WatchRemoteConfig success")
go func() {
for {
<-ch
// updated
cfg.Unmarshal(testCfg)
}
}()
}
Output: WatchRemoteConfig success