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() }
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 }
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) }
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 }
// 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) * */ }
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() }
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 }
func getConfig() { log := logging.MustGetLogger("log") if err := viper.Unmarshal(&C); err != nil { log.Critical("Unable to translate config file:", err) os.Exit(1) } }
func Fetcher() { var config Config if err := viper.Unmarshal(&config); err != nil { fmt.Println(err) } for _, feed := range config.Feeds { go PollFeed(feed) } }
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) }
// 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") }
// 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() }
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) }
// 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()) }
// 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) }
// 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 }
// 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) }
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") }
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) } }
func getConfig() (cfg Config) { viper.SetEnvPrefix(NAME) viper.AutomaticEnv() viper.SetConfigType("json") viper.SetConfigName("viperconfig") viper.AddConfigPath("/etc/" + NAME + "/") viper.AddConfigPath(".") err := viper.ReadInConfig() if err != nil { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } viper.Set("mission.inception", time.Now()) viper.SetDefault("output.format", "json") viper.Unmarshal(&cfg) return cfg }
// InitConfig initiliaze configuration file func InitConfig(filename string) (*Config, *Error) { viper.SetConfigType("YAML") f, err := os.Open(filename) if err != nil { return nil, &Error{"could not read configuration files."} } err = viper.ReadConfig(f) if err != nil { return nil, &Error{"configuration format is not correct."} } var config Config err = viper.Unmarshal(&config) if err != nil { glog.Errorf("Cannot read configuration. Reason: %s", err) return nil, &Error{"cannot read configuration, something must be wrong."} } return &config, nil }
func loadConfiguration() Configuration { var conf Configuration viper.SetConfigType("properties") viper.SetConfigName("edisonIsThePilot") // name of config file (without extension) viper.AddConfigPath("/etc") // path to look for the config file in setDefaultValues() err := viper.ReadInConfig() // Find and read the config file if err != nil { // Handle errors reading the config file log.Warning("Unable to read the configuration file /etc/edisonIsThePilot.properties. Using default values.") } err = viper.Unmarshal(&conf) if err != nil { // Handle errors reading the config file log.Panic("Unable to load configuration. Check /etc/edisonIsThePilot.properties file") } log.Info("Configuration is: %#v", conf) return conf }
func LoadConfigFrom(configPath string) (ConfigStruct, error) { config := ConfigStruct{} viper := viper.New() basename := filepath.Base(configPath) viper.SetConfigName(strings.TrimSuffix(basename, filepath.Ext(basename))) viper.AddConfigPath(filepath.Dir(configPath)) err := viper.ReadInConfig() if err != nil { return config, err } err = viper.Unmarshal(&config) if err != nil { return config, err } return config, nil }
func readConfig() error { viper.SetConfigType("yaml") viper.SetDefault("proxyList", "/etc/proxy.list") viper.SetDefault("check", map[string]interface{}{ "url": "http://ya.ru", "string": "yandex", "interval": "60m", "timeout": "5s", }) viper.SetDefault("bind", "0.0.0.0:8080") viper.SetDefault("workersCount", 20) viper.SetDefault("maxTry", 3) viper.SetDefault("debug", false) var configFile = flag.StringP("config", "c", "/etc/"+appName+".yaml", "full path to config") var showVersion = flag.BoolP("version", "v", false, "version") flag.Parse() if *showVersion { log.Println(appVersion) os.Exit(0) } file, err := ioutil.ReadFile(*configFile) if err != nil { return err } err = viper.ReadConfig(bytes.NewReader(file)) if err != nil { return err } err = viper.Unmarshal(&cfg) if err != nil { return err } return nil }
func (ui *tatui) loadConfig() { internal.ReadConfig() filters := viper.GetStringSlice("filters") // no range to keep order for index := 0; index < len(filters); index++ { filter := filters[index] tuples := strings.Split(filter, " ") if len(tuples) <= 2 { continue } topic := tuples[1] if _, ok := ui.currentFilterMessages[topic]; !ok { ui.currentFilterMessages[topic] = make(map[int]*tat.MessageCriteria) ui.currentFilterMessagesText[topic] = make(map[int]string) } c, criteriaText := ui.prepareFilterMessages(strings.Join(tuples[2:], " "), tuples[0], topic) ui.currentFilterMessages[topic][len(ui.currentFilterMessages[topic])] = c ui.currentFilterMessagesText[topic][len(ui.currentFilterMessagesText[topic])] = criteriaText } commands := viper.GetStringSlice("commands") // no range to keep order for index := 0; index < len(commands); index++ { commandsOnTopic := commands[index] tuples := strings.Split(strings.TrimSpace(commandsOnTopic), " ") if len(tuples) <= 1 { continue } topic := tuples[0] ui.uiTopicCommands[topic] = commandsOnTopic[len(topic):] } var conf config.TemplateJSONType err := viper.Unmarshal(&conf) if err != nil { internal.Exit("unable to decode confif file, err: %v", err) } ui.hooks = conf.Hooks }
// 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.SetConfigType("yaml") viper.SetConfigName(".runes") // name of config file (without extension) viper.AddConfigPath("$HOME") // adding home directory as first search path viper.SetEnvPrefix("runes") // so viper.AutomaticEnv will get matching envvars starting with O2M_ viper.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) if err := viper.Unmarshal(&C); err != nil { panic(err) } } else { fmt.Println("Configuration file ~/.runes.yaml not found, using default settings.") C.Port = 8086 C.Auth.Type = config.AuthNone } if C.DataDir == "" { usr, err := user.Current() if err != nil { log.Fatal(err) } C.DataDir = usr.HomeDir + "/.runes" } if C.TmpDir == "" { C.TmpDir = "/tmp/runes/tmp" } if C.CacheDir == "" { C.CacheDir = "/tmp/runes/cache" } }
func (c *Conf) Update() { log.Println("Updating config") //Legacy config for client //need to be replaced by aliases after this PR will be integrated into viper: //https://github.com/spf13/viper/pull/155 UpdateLegacyString("seed", "endpointuri") UpdateLegacyString("secure_token", "token") UpdateLegacyBool("server_enabled", "serverEnabled", false) viper.Unmarshal(c) if c.EnableLdap { c.setupLdapViper() c.ldapViper.ReadInConfig() c.ldapViper.Unmarshal(c.ldapConfig) } c.AutoRepair() if c.Debug { log.Printf("Configuration: %+v", c) } }
func NewBalancerCommand() *cobra.Command { cmd := &cobra.Command{ Use: "balancer [options]", Short: "starts a new balancer", Long: `fusis balancer is the command used to run the balancer process. It's responsible for creating new Services and watching for Agents joining the cluster, and add routes to them in the Load Balancer.`, PreRun: func(cmd *cobra.Command, args []string) { viper.Unmarshal(&conf) }, Run: balancerCommandFunc, } setupDefaultOptions() setupBalancerCmdFlags(cmd) level, _ := log.ParseLevel(strings.ToUpper(conf.LogLevel)) log.Info(log.WarnLevel, level) log.SetLevel(log.DebugLevel) return cmd }
func mainCommand(cmd *cobra.Command, args []string) { err := viper.Unmarshal(&c) if err != nil { log.Fatalf("Unable to marshal configuration: %v", err) } if !viper.IsSet("dbpath") { log.Fatalf("Please set the dbpath configuration option or EVEINDY_DBPATH " + "environment variable to the database's path.") } if !(viper.IsSet("CookieDomain") && viper.IsSet("CookiePath")) { log.Fatalf("Please set the CookieDomain and CookiePath configuration options.") } if !(viper.IsSet("ClientID") && viper.IsSet("ClientSecret") && viper.IsSet("RedirectURL")) { log.Fatalf("Please set the ClientID, ClientSecret, and RedirectURL configuration " + "options as registered with CCP.") } // workaround for viper bug // c.Dev = viper.GetBool("Dev") sde := dbaccess.SQLDatabase(c.DbDriver, c.DbPath) var myCache evego.Cache switch c.Cache { case "inproc": myCache = server.InMemCache() case "redis": if c.RedisPassword != "" { myCache = cache.RedisCache(c.RedisHost, c.RedisPassword) } else { myCache = cache.RedisCache(c.RedisHost) } default: log.Fatalf( "The Cache configuration option must be set to \"inproc\" (default) or \"redis\".") } xmlAPI := eveapi.XML(c.XMLAPIEndpoint, sde, myCache) localdb, err := db.Interface(c.DbDriver, c.DbPath, xmlAPI) if err != nil { log.Fatalf("Unable to connect to local database: %v", err) } var router evego.Router switch c.Router { case "evecentral": router = routing.EveCentralRouter( "http://api.eve-central.com/api/route", myCache) case "sql": router = routing.SQLRouter(c.DbDriver, c.DbPath, myCache) default: log.Fatalf( "The Router configuration option must be set to \"evecentral\" (default) or \"sql\".") } eveCentralMarket := market.EveCentral(sde, router, xmlAPI, "http://api.eve-central.com/api/quicklook", myCache) sessionizer := server.GetSessionizer(c.CookieDomain, c.CookiePath, !c.Dev, localdb) mux := newMux() setRoutes(mux, sde, localdb, xmlAPI, eveCentralMarket, sessionizer, myCache) // Set up internal bits. // Start background jobs. server.StartJobs(localdb) serve(mux, c.BindProtocol, c.Bind) }
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)) } } }) }