当前位置: 首页>>代码示例>>Golang>>正文


Golang viper.Unmarshal函数代码示例

本文整理汇总了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))
			}
		}
	})
}
开发者ID:jqs7,项目名称:Shan8Bot,代码行数:33,代码来源:init.go

示例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()
}
开发者ID:BIT66COM,项目名称:gateway-server,代码行数:30,代码来源:main.go

示例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
}
开发者ID:kytrinyx,项目名称:venom-example,代码行数:27,代码来源:config.go

示例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)
	*
	 */
}
开发者ID:olegshaldybin,项目名称:kubernetes,代码行数:33,代码来源:test_context.go

示例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
}
开发者ID:bep,项目名称:alfn,代码行数:47,代码来源:root.go

示例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()
}
开发者ID:FihlaTV,项目名称:bridge-server,代码行数:28,代码来源:main.go

示例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
}
开发者ID:redfit,项目名称:alfred-google-translation-workflow,代码行数:27,代码来源:config.go

示例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)
}
开发者ID:Dataman-Cloud,项目名称:zookeeper-helper,代码行数:29,代码来源:config.go

示例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)
	}
}
开发者ID:Chipsterjulien,项目名称:filterIPDyn,代码行数:8,代码来源:app.go

示例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)
	}
}
开发者ID:LC2010,项目名称:firstGoApp-Planet,代码行数:10,代码来源:fetch.go

示例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)
}
开发者ID:Bowbaq,项目名称:scala-imports,代码行数:11,代码来源:main.go

示例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")

}
开发者ID:e-gov,项目名称:fox,代码行数:55,代码来源:Config.go

示例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()
}
开发者ID:jemacom,项目名称:hydra,代码行数:53,代码来源:root.go

示例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)
}
开发者ID:ssola,项目名称:resizer,代码行数:15,代码来源:resizer.go

示例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())
}
开发者ID:livenson,项目名称:fox,代码行数:49,代码来源:Config.go


注:本文中的github.com/spf13/viper.Unmarshal函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。