• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang viper.Unmarshal函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/spf13/viper.Unmarshal函数的典型用法代码示例。如果您正苦于以下问题:Golang Unmarshal函数的具体用法?Golang Unmarshal怎么用?Golang Unmarshal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Unmarshal函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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: 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


示例6: 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


示例7: 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


示例8: 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


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


示例16: Load

// Load loads the config file at path and environment variables into a Config.
// The config file can be in any standard format (JSON, YAML, etc).
// The keys in the config file should match the key listed in the "mapstructure" struct tag in the preprocessedConfig struct.
// Keys can also be set as environment variables. Simply attach UTEACH_ to the beginning and capitalize the entire key.
// All keys must be set (even as an empty string) in the config file, even if the key is set as an env variable.
func Load(path string) (*Config, error) {
	if err := loadViper(path); err != nil {
		return nil, err
	}

	preprocessed := new(preprocessedConfig)
	if err := viper.Unmarshal(preprocessed); err != nil {
		return nil, err
	}

	conf := new(Config)
	conf.HTTPAddress = preprocessed.HTTPAddress

	// for file paths, if it is relative we want the path to be relative to the config's path and not the cwd
	dir := filepath.Dir(path)
	conf.DBPath = joinIfNotAbs(dir, preprocessed.DBPath)
	conf.TemplatesPath = joinIfNotAbs(dir, preprocessed.TemplatesPath)
	conf.StaticFilesPath = joinIfNotAbs(dir, preprocessed.StaticFilesPath)

	var err error
	conf.CookieAuthenticationKey, err = base64.StdEncoding.DecodeString(preprocessed.CookieAuthenticationKeyBase64)
	if err != nil {
		return nil, err
	}

	conf.CookieEncryptionKey, err = base64.StdEncoding.DecodeString(preprocessed.CookieEncryptionKeyBase64)
	if err != nil {
		return nil, err
	}

	oauth2Config := &oauth2.Config{
		ClientID:     preprocessed.OAuth2ClientID,
		ClientSecret: preprocessed.OAuth2ClientSecret,
		RedirectURL:  preprocessed.OAuth2RedirectURL,
		Scopes:       []string{"openid", "name", "email", "nickname"},
		Endpoint: oauth2.Endpoint{
			AuthURL:  authURL,
			TokenURL: tokenURL,
		},
	}

	conf.OAuth2 = oauth2Config
	conf.OAuth2UserInfoURL = userInfoURL

	return conf, nil
}
开发者ID:BrianHarringtonUTSC,项目名称:uTeach,代码行数:51,代码来源:config.go


示例17: initConfig

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".nodetree") // 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) && !pSilent {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}

	viper.Unmarshal(&stageTree)

}
开发者ID:msutter,项目名称:nodetree,代码行数:18,代码来源:root.go


示例18: ViperizeFlags

// ViperizeFlags sets up all flag and config processing. Future configuration info should be added to viper, not to flags.
func ViperizeFlags() {

	// Part 1: Set regular flags.
	// TODO: Future, lets eliminate e2e 'flag' deps entirely in favor of viper only,
	// since go test 'flag's are sort of incompatible w/ flag, glog, etc.
	RegisterCommonFlags()
	RegisterClusterFlags()
	flag.Parse()

	// Part 2: Set Viper provided flags.
	// This must be done after common flags are registered, since Viper is a flag option.
	viper.SetConfigName(TestContext.Viper)
	viper.AddConfigPath(".")
	viper.ReadInConfig()

	// TODO Consider wether or not we want to use overwriteFlagsWithViperConfig().
	viper.Unmarshal(&TestContext)
}
开发者ID:kubernetes,项目名称:kubernetes,代码行数:19,代码来源:test_context.go


示例19: main

func main() {
	viper.SetConfigName("config")
	viper.AddConfigPath("/etc/labelmaker/")
	viper.AddConfigPath(".")
	viper.SetDefault("RedisHost", "localhost:6379")
	viper.SetDefault("RedisDb", 1)
	var err error
	if err = viper.ReadInConfig(); err != nil {
		log.Fatal(err)
	}
	if err = viper.Unmarshal(&appConfig); err != nil {
		log.Fatal(err)
	}

	pool = newRedisPool(appConfig.RedisHost, appConfig.RedisDb)
	if templateManager, err = temple.New(appConfig.DevMode, templates, "templates"); err != nil {
		log.Fatal(err)
	}
	if !appConfig.DevMode {
		gin.SetMode(gin.ReleaseMode)
	}
	r := gin.Default()
	conf := &ghauth.Conf{
		ClientId:     appConfig.GithubClientID,
		ClientSecret: appConfig.GithubClientSecret,
		Scopes:       []string{"user", "read:public_key", "repo"},
		CookieName:   "ghauth",
		CookieSecret: appConfig.CookieSecret,
	}
	auth := ghauth.New(conf)
	auth.RegisterRoutes("/login", "/callback", "/logout", r)
	r.Use(renderError)
	r.Use(auth.AuthCheck())

	r.GET("/", home)
	r.POST("/hooks/:hook", onHook)

	locked := r.Group("/", auth.RequireAuth())
	locked.GET("/repo/:owner/:name", repo)
	locked.POST("/install/:owner/:name", install)

	r.Run(":9999")
}
开发者ID:captncraig,项目名称:labelmaker,代码行数:43,代码来源:main.go


示例20: initConfig

func initConfig() {
	if CfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(CfgFile)
	}

	viper.SetConfigName("config")
	viper.AddConfigPath("/etc/rex/")
	viper.AddConfigPath("$HOME/.rex")
	viper.AddConfigPath(".")
	viper.AutomaticEnv()

	if err := viper.ReadInConfig(); err != nil {
		log.Fatalf("Fatal error: config file: %s \n", err)
	}

	if err := viper.Unmarshal(&Config); err != nil {
		log.Fatalf("Unable to decode config into struct, %s \n", err)
	}
}
开发者ID:beanworks,项目名称:rex,代码行数:19,代码来源:rex.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang viper.WatchConfig函数代码示例发布时间:2022-05-28
下一篇:
Golang viper.SetEnvPrefix函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap