本文整理汇总了Golang中github.com/spf13/viper.Unmarshal函数的典型用法代码示例。如果您正苦于以下问题:Golang Unmarshal函数的具体用法?Golang Unmarshal怎么用?Golang Unmarshal使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Unmarshal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: init
func init() {
viper.SetConfigName("conf")
viper.AddConfigPath(".")
viper.WatchConfig()
viper.ReadInConfig()
viper.Unmarshal(&conf)
viper.OnConfigChange(func(e fsnotify.Event) {
if err := viper.Unmarshal(&conf); err != nil {
log.Println(err.Error())
} else {
log.Println("config auto reload!")
}
})
r = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: conf.RedisPass,
})
scheduler.Every().Day().At("00:00").Run(func() {
if time.Now().Day() == 1 {
length := r.ZCard("Shan8Bot:K").Val()
if length < 25 {
return
}
i := rand.Int63n(length-25) + 25
for _, v := range r.ZRangeWithScores("Shan8Bot:K", i, i).Val() {
log.Println("add 100K for ", v.Member)
r.ZIncrBy("Shan8Bot:K", 100, v.Member.(string))
}
}
})
}
示例2: run
func run(cmd *cobra.Command, args []string) {
log.Print("Reading config.toml file")
err := viper.ReadInConfig()
if err != nil {
log.Fatal("Error reading config file: ", err)
}
var config config.Config
err = viper.Unmarshal(&config)
err = config.Validate()
if err != nil {
log.Fatal(err.Error())
return
}
if migrateFlag {
migrate(config)
return
}
app, err = gateway.NewApp(config)
if err != nil {
log.Fatal(err.Error())
return
}
app.Serve()
}
示例3: NewConfig
func NewConfig() (*Config, error) {
flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
c := Config{}
flags.StringVarP(&c.URL, "url", "u", "", "the url")
viper.BindPFlag("url", flags.Lookup("url"))
// This doesn't need to be in the Config struct, because we're just using it to override viper.
file := flags.StringP("file", "f", "", "name of the config file")
// Parse the command line args into the flag set, ignoring the command name.
flags.Parse(os.Args[1:])
if *file != "" {
viper.SetConfigFile(*file)
}
if err := viper.ReadInConfig(); err != nil {
return nil, err
}
if err := viper.Unmarshal(&c); err != nil {
return nil, err
}
return &c, nil
}
示例4: ViperizeFlags
// Enable viper configuration management of flags.
func ViperizeFlags() {
// TODO @jayunit100: Maybe a more elegant viper-flag integration for the future?
// For now, we layer it on top, because 'flag' deps of 'go test' make pflag wrappers
// fragile, seeming to force 'flag' to have deep awareness of pflag params.
RegisterCommonFlags()
RegisterClusterFlags()
flag.Parse()
// Add viper in a minimal way.
// Flag interop isnt possible, since 'go test' coupling to flag.Parse.
// This must be done after common flags are registered, since Viper is a flag option.
viper.SetConfigName(TestContext.Viper)
viper.AddConfigPath(".")
viper.ReadInConfig()
viper.Unmarshal(&TestContext)
/** This can be used to overwrite a flag value.
*
* viperFlagSetter := func(f *flag.Flag) {
* if viper.IsSet(f.Name) {
* glog.V(4).Infof("[viper config] Overwriting, found a settting for %v %v", f.Name, f.Value)
* viper.Unmarshal(&TestContext)
* // f.Value.Set(viper.GetString(f.Name))
* }
* }
* // Each flag that we've declared can be set via viper.
* flag.VisitAll(viperFlagSetter)
*
*/
}
示例5: startup
func startup() error {
var config lib.Config
if err := viper.Unmarshal(&config); err != nil {
return err
}
serverAndPort := fmt.Sprintf("%s:%d", serverInterface, serverPort)
if config.Feed.Link == "" {
config.Feed.Link = "http://" + serverAndPort
}
if config.Feed.MaxItems <= 0 {
config.Feed.MaxItems = 10
}
// enable live reloading of config
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config", e.Name, "changed ...")
if err := viper.Unmarshal(&config); err != nil {
fmt.Println("error: Failed to reload config: ", err)
return
}
shutdownIfNeededAndStart(config)
})
viper.WatchConfig()
shutdownIfNeededAndStart(config)
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/rss+xml; charset=utf-8")
fmt.Fprintf(w, app().GetFeed())
})
fmt.Printf("\nStarting server on http://%s ...\n\n", serverAndPort)
graceful.Run(serverAndPort, 10*time.Second, mux)
app().Shutdown()
fmt.Println("\nStopped ...")
return nil
}
示例6: run
func run(cmd *cobra.Command, args []string) {
err := viper.ReadInConfig()
if err != nil {
log.Fatal("Error reading config_compliance.toml file: ", err)
}
var config config.Config
err = viper.Unmarshal(&config)
err = config.Validate()
if err != nil {
log.Fatal(err.Error())
return
}
if config.LogFormat == "json" {
log.SetFormatter(&log.JSONFormatter{})
}
app, err = compliance.NewApp(config, migrateFlag)
if err != nil {
log.Fatal(err.Error())
return
}
app.Serve()
}
示例7: saveConfig
func saveConfig() error {
var marshaledConfig config
configPath := getDefaultConfigPath()
viper.Unmarshal(&marshaledConfig)
buf, err := json.MarshalIndent(marshaledConfig, "", " ")
if err != nil {
return err
}
err = os.MkdirAll(configPath, 0755)
if err != nil {
return err
}
f, err := os.Create(filepath.Join(configPath, "config.json"))
if err != nil {
return err
}
defer f.Close()
f.WriteString(string(buf))
return nil
}
示例8: init
func init() {
jww.SetLogThreshold(jww.LevelTrace)
jww.SetStdoutThreshold(jww.LevelInfo)
log.Println("initing config ...")
viper.SetConfigName("zookeeper-helper")
viper.AddConfigPath("./")
viper.AddConfigPath("$HOME/.omega/")
viper.AddConfigPath("/etc/omega/")
viper.SetConfigType("yaml")
if err := viper.ReadInConfig(); err != nil {
log.Panicln("can't read config file:", err)
}
initDefault()
if err := viper.Unmarshal(&pairs); err != nil {
log.Panicln("can't covert to config pairs: ", err)
}
if !pairs.Debugging {
jww.SetLogThreshold(jww.LevelError)
jww.SetStdoutThreshold(jww.LevelError)
}
log.Printf("initialized config pairs: %+v\n", pairs)
}
示例9: getConfig
func getConfig() {
log := logging.MustGetLogger("log")
if err := viper.Unmarshal(&C); err != nil {
log.Critical("Unable to translate config file:", err)
os.Exit(1)
}
}
示例10: Fetcher
func Fetcher() {
var config Config
if err := viper.Unmarshal(&config); err != nil {
fmt.Println(err)
}
for _, feed := range config.Feeds {
go PollFeed(feed)
}
}
示例11: init
func init() {
viper.SetConfigName(".fix-imports")
viper.AddConfigPath(".")
viper.AddConfigPath("$HOME")
if err := viper.ReadInConfig(); err != nil {
fmt.Println("Error reading config file: %s\n", err)
os.Exit(-1)
}
viper.Unmarshal(&config)
}
示例12: LoadConfigByPathWOExtension
// LoadConfigByName loads a config from a specific file
// Used for separating test from operational configuration
func LoadConfigByPathWOExtension(name string) {
var isFatal bool
var tmp *Config
tmp = new(Config)
cLock.RLock()
isFatal = (config == nil)
cLock.RUnlock()
viper.SetConfigName(name)
viper.SetConfigType("json")
userConfigFolder := getUserConfigFolderPath()
configFolder := getConfigFolderPath()
if userConfigFolder != "" {
viper.AddConfigPath(userConfigFolder) // user's own personal config file
}
if configFolder != "" {
viper.AddConfigPath(configFolder) // General fallback config file
}
if err := viper.ReadInConfig(); err != nil {
// No config to start up on
if isFatal {
log.Debugf("Failed to find config in: %s (user) or %s (fallback)",
userConfigFolder, configFolder)
panic(err)
} else {
log.Errorf("Failed to load configuration from %s\n", name)
return
}
}
viper.Unmarshal(tmp)
sanitize(tmp)
cLock.Lock()
if config == nil {
tmp.Version = 1
} else {
tmp.Version = config.Version + 1
}
config = tmp
cLock.Unlock()
log.WithFields(log.Fields{
"path": viper.ConfigFileUsed(),
"confVersion": config.Version,
}).Info("Success loading configuration")
}
示例13: initConfig
// initConfig reads in config file and ENV variables if set.
func initConfig() {
mutex.Lock()
if cfgFile != "" {
// enable ability to specify config file via flag
viper.SetConfigFile(cfgFile)
}
path := absPathify("$HOME")
if _, err := os.Stat(filepath.Join(path, ".hydra.yml")); err != nil {
_, _ = os.Create(filepath.Join(path, ".hydra.yml"))
}
viper.SetConfigType("yaml")
viper.SetConfigName(".hydra") // name of config file (without extension)
viper.AddConfigPath("$HOME") // adding home directory as first search path
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err != nil {
fmt.Printf(`Config file not found because "%s"`, err)
fmt.Println("")
}
if err := viper.Unmarshal(c); err != nil {
fatal("Could not read config because %s.", err)
}
if consentURL, ok := viper.Get("CONSENT_URL").(string); ok {
c.ConsentURL = consentURL
}
if clientID, ok := viper.Get("CLIENT_ID").(string); ok {
c.ClientID = clientID
}
if systemSecret, ok := viper.Get("SYSTEM_SECRET").(string); ok {
c.SystemSecret = []byte(systemSecret)
}
if clientSecret, ok := viper.Get("CLIENT_SECRET").(string); ok {
c.ClientSecret = clientSecret
}
if databaseURL, ok := viper.Get("DATABASE_URL").(string); ok {
c.DatabaseURL = databaseURL
}
if c.ClusterURL == "" {
fmt.Printf("Pointing cluster at %s\n", c.GetClusterURL())
}
mutex.Unlock()
}
示例14: main
func main() {
// Load configuration
viper.SetConfigName("config")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
panic(fmt.Errorf("Fatal error loading configuration file: %s", err))
}
// Marshal the configuration into our Struct
viper.Unmarshal(&config)
http.HandleFunc("/resize", resizing)
http.ListenAndServe(fmt.Sprintf(":%d", config.Port), nil)
}
示例15: LoadConfigByName
// LoadConfigByName loads a config from a specific file
// Used for separating test from operational configuration
func LoadConfigByName(name string) {
var isFatal bool
var tmp *Config
tmp = new(Config)
cLock.RLock()
isFatal = (config == nil)
cLock.RUnlock()
viper.SetConfigName(name)
viper.SetConfigType("json")
configFolder := getUserConfigFolderPath()
viper.AddConfigPath(configFolder)
viper.AddConfigPath(".") // default path
if err := viper.ReadInConfig(); err != nil {
// No config to start up on
if isFatal {
log.Debugf("Looking for config in: %s", configFolder)
panic(err)
} else {
log.Errorf("Failed to load configuration from %s\n", name)
return
}
}
log.Infof("Config file found: %s\n", viper.ConfigFileUsed())
viper.Unmarshal(tmp)
sanitize(tmp)
// TODO viper can reload config too. Remove this?
// Nope, the versioning is so we can trigger reloading of keys
cLock.Lock()
if config == nil {
tmp.Version = 1
} else {
tmp.Version = config.Version + 1
}
config = tmp
cLock.Unlock()
log.Infof("Success loading configuration ver %d from %s", config.Version, viper.ConfigFileUsed())
}