// LoadConfig loads the config into the Config Struct and returns the // ConfigStruct object. Will load from environmental variables (all caps) if we // set a flag to true. func LoadConfig() ConfigStruct { viper.SetConfigName("config") viper.SetConfigType("yaml") viper.AddConfigPath(".") viper.AddConfigPath("../") viper.AddConfigPath("/etc/") viper.AddConfigPath("$GOPATH/src/github.com/GrappigPanda/notorious/") err := viper.ReadInConfig() if err != nil { panic("Failed to open config file") } if viper.GetBool("UseEnvVariables") == true { viper.AutomaticEnv() viper.BindEnv("dbuser") } whitelist, err := strconv.ParseBool(viper.Get("whitelist").(string)) if err != nil { whitelist = false } return loadSQLOptions(whitelist) }
func TestDiscoveryFactory(t *testing.T) { viper.SetConfigType("yaml") yaml := []byte(` nuvem.discovery.testdsl.static.servers: - localhost:8080 - 127.0.0.1:9080 `) err := viper.ReadConfig(bytes.NewBuffer(yaml)) viper.SetDefault("nuvem.discovery.testdsl.factory", discovery.StaticFactoryKey) viper.SetDefault("nuvem.loadbalancer.serverlist.testdsl.factory", DisoveryFactoryKey) if err != nil { // Handle errors reading the config file panic(fmt.Errorf("Fatal error config file: %s \n", err)) } // servers := viper.GetStringSlice("nuvem.loadbalancer.test.static.servers") // fmt.Printf("%+v\n", servers) // factory := viper.GetString("nuvem.loadbalancer.test.factory") // fmt.Printf("%+v\n", factory) serverList := Create("testdsl") servers := assertServerList(t, serverList, 2) assertServer(t, servers[0], "localhost", 8080) assertServer(t, servers[1], "127.0.0.1", 9080) }
func newConfig() *Conf { c := new(Conf) c.ldapViper = viper.New() c.ldapConfig = &LdapConfig{} c.notificationConfigs = []NotificationServiceConfig{} viper.SetConfigName("indispenso") viper.SetEnvPrefix("ind") // Defaults viper.SetDefault("Token", "") viper.SetDefault("Hostname", getDefaultHostName()) viper.SetDefault("UseAutoTag", true) viper.SetDefault("ServerEnabled", false) viper.SetDefault("Home", defaultHomePath) viper.SetDefault("Debug", false) viper.SetDefault("ServerPort", 897) viper.SetDefault("EndpointURI", "") viper.SetDefault("SslCertFile", "cert.pem") viper.SetDefault("SslPrivateKeyFile", "key.pem") viper.SetDefault("AutoGenerateCert", true) viper.SetDefault("ClientPort", 898) viper.SetDefault("EnableLdap", false) viper.SetDefault("LdapConfigFile", "") //Flags c.confFlags = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError) configFile := c.confFlags.StringP("config", "c", "", "Config file location default is /etc/indispenso/indispenso.{json,toml,yaml,yml,properties,props,prop}") c.confFlags.BoolP("serverEnabled", "s", false, "Define if server module should be started or not") c.confFlags.BoolP("debug", "d", false, "Enable debug mode") c.confFlags.StringP("home", "p", defaultHomePath, "Home directory where all config files are located") c.confFlags.StringP("endpointUri", "e", "", "URI of server interface, used by client") c.confFlags.StringP("token", "t", "", "Secret token") c.confFlags.StringP("hostname", "i", getDefaultHostName(), "Hostname that is use to identify itself") c.confFlags.BoolP("enableLdap", "l", false, "Enable LDAP authentication") c.confFlags.BoolP("help", "h", false, "Print help message") c.confFlags.Parse(os.Args[1:]) if len(*configFile) > 2 { viper.SetConfigFile(*configFile) } else { legacyConfigFile := "/etc/indispenso/indispenso.conf" if _, err := os.Stat(legacyConfigFile); err == nil { viper.SetConfigFile(legacyConfigFile) viper.SetConfigType("yaml") } } viper.BindPFlags(c.confFlags) viper.AutomaticEnv() viper.ReadInConfig() c.setupHome(nil, viper.GetString("Home")) c.setupHome(c.ldapViper, viper.GetString("Home")) c.SetupNotificationConfig("slack", &SlackNotifyConfig{}) c.Update() return c }
func loadConfig() { stormpath.InitLog() viper.SetConfigType("yaml") viper.AutomaticEnv() //Load bundled default config defaultConfig, err := Asset("config/web.stormpath.yaml") if err != nil { stormpath.Logger.Panicf("[ERROR] Couldn't load default bundle configuration: %s", err) } viper.ReadConfig(bytes.NewBuffer(defaultConfig)) //Merge users custom configuration viper.SetConfigFile("stormpath.yaml") viper.AddConfigPath("~/.stormpath/") viper.AddConfigPath(".") err = viper.MergeInConfig() if err != nil { stormpath.Logger.Println("[WARN] User didn't provide custom configuration") } Config.Produces = viper.GetStringSlice("stormpath.web.produces") Config.BasePath = viper.GetString("stormpath.web.basePath") loadSocialConfig() loadCookiesConfig() loadEndpointsConfig() loadOAuth2Config() }
func init() { currentUser, err := user.Current() if err != nil { panic(err) } userHomeDir := currentUser.HomeDir fileSeperator := string(filepath.Separator) ConfigDirectory = userHomeDir + fileSeperator + ".config" + fileSeperator + "pact" + fileSeperator ConfigFileName = "pact" ConfigFileType = "json" viper.SetConfigType(ConfigFileType) viper.SetConfigName(ConfigFileName) viper.AddConfigPath(ConfigDirectory) err = viper.ReadInConfig() if err != nil { fmt.Println("No config file found. The config command will generate one.") } else { HydrateConfigurationModel() } }
// initConfig reads in config file and ENV variables if set. func initConfig(cmd *cobra.Command) { viper.SetConfigName(".skelly") // name of config file (without extension) viper.AddConfigPath("$HOME") // adding home directory as first search path viper.SetConfigType("json") viper.AutomaticEnv() // read in environment variables that match fmt.Println("got here") // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) } // Make sure that go src var is set gopath = viper.GetString("gopath") if len(gopath) <= 0 { gopath = joinPath(os.Getenv("GOPATH"), "src") viper.Set("gopath", gopath) } if cmd.Flags().Lookup("project-root").Changed { viper.Set("project-root", basePath) } if cmd.Flags().Lookup("author").Changed { fmt.Println("adding author") viper.Set("author", author) } if cmd.Flags().Lookup("email").Changed { viper.Set("email", email) } fmt.Println(email) if cmd.Flags().Lookup("license").Changed { viper.Set("license", license) } }
func main() { viper.SetDefault("ConfigFile", "$HOME/.krb.jira.json") viper.SetConfigName(".krb.jira") viper.SetConfigType("json") //viper.AddConfigPath("$HOME") viper.AddConfigPath(".") viper.ReadInConfig() fmt.Printf("host:%s\n", viper.GetString("host")) fmt.Printf("port:%d\n", viper.GetInt("port")) fmt.Printf("user:%s\n", viper.GetString("user")) fmt.Printf("pass:%s\n", viper.GetString("pass")) apiInfo := &JiraApiInfo{} viper.MarshalKey("apiInfo", &apiInfo) fmt.Printf("apiInfo:%q\n", apiInfo) // NB: marshaling this whole struct doesn't seem to work? /* config := &ConfigInfo{} err := viper.Marshal(&config) if err != nil { panic(err) } fmt.Printf("config:%q\n", config) */ }
// Setup sets up defaults for viper configuration options and // overrides these values with the values from the given configuration file // if it is not empty. Those values again are overwritten by environment // variables. func Setup(configFilePath string) error { viper.Reset() // Expect environment variables to be prefix with "ALMIGHTY_". viper.SetEnvPrefix("ALMIGHTY") // Automatically map environment variables to viper values viper.AutomaticEnv() // To override nested variables through environment variables, we // need to make sure that we don't have to use dots (".") inside the // environment variable names. // To override foo.bar you need to set ALM_FOO_BAR viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) viper.SetTypeByDefaultValue(true) setConfigDefaults() // Read the config // Explicitly specify which file to load config from if configFilePath != "" { viper.SetConfigFile(configFilePath) viper.SetConfigType("yaml") err := viper.ReadInConfig() // Find and read the config file if err != nil { // Handle errors reading the config file return fmt.Errorf("Fatal error config file: %s \n", err) } } return nil }
func configInit() { viper.SetEnvPrefix("srb") var configPath string flag.StringVar(&configPath, "config", "", "Path of configuration file without name (name must be config.yml)") flag.Parse() if len(configPath) > 0 { viper.AddConfigPath(configPath) } configPath = os.Getenv("SRB_CONFIG") if len(configPath) > 0 { viper.AddConfigPath(configPath) } viper.AddConfigPath("/etc/slack-redmine-bot/") viper.AddConfigPath(".") viper.SetConfigName("config") viper.SetConfigType("yaml") err := viper.ReadInConfig() if err != nil { panic(fmt.Errorf("Error in config file. %s \n", err)) } }
func main() { if len(os.Args) != 2 { fmt.Println("Invalid command usage\n") showUsage() os.Exit(1) } arg := os.Args[1] viper.SetConfigName("config") viper.SetConfigType("toml") viper.AddConfigPath("./") err := viper.ReadInConfig() if err != nil { fmt.Println(err) os.Exit(1) } switch arg { case "bootstrap": npi.Bootstrap() case "fetch": npi.Fetch() case "drop": npi.Drop() case "search-index": npi.SearchIndex() default: fmt.Println("Invalid command:", arg) showUsage() os.Exit(1) } }
func init() { viper.SetConfigName("telebot") viper.SetConfigType("yaml") viper.AddConfigPath(".") viper.AddConfigPath("$HOME/.telebot") err := viper.ReadInConfig() if err != nil { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", viper.GetString("mysql.telebot.user"), viper.GetString("mysql.telebot.password"), viper.GetString("mysql.telebot.host"), viper.GetString("mysql.telebot.port"), viper.GetString("mysql.telebot.dbname")) db, err = sql.Open("mysql", dsn) checkErr(err) err = db.Ping() checkErr(err) go func() { tick := time.Tick(rTime * time.Second) for range tick { if err := db.Ping(); err != nil { log.Println("Connection to DB lost (try reconnect after", rTime, "seconds)") } } }() }
// Init calls flag.Parse() and, for now, sets up the // credentials. func (cs *CliState) Init() error { cs.flagSet.Parse(os.Args[1:]) config.SetConfigName(".romana") // name of config file (without extension) config.SetConfigType("yaml") config.AddConfigPath("$HOME") // adding home directory as first search path config.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. err := config.ReadInConfig() if err != nil { switch err := err.(type) { case config.ConfigFileNotFoundError: // For now do nothing case *os.PathError: if err.Error() != "open : no such file or directory" { return err } default: return err } } log.Infof("Using config file: %s", config.ConfigFileUsed()) err = cs.credential.Initialize() return err }
func main() { viper.AutomaticEnv() viper.SetConfigName("obcca") viper.SetConfigType("yaml") viper.AddConfigPath("./") err := viper.ReadInConfig() if err != nil { panic(err) } obcca.LogInit(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr, os.Stdout) eca := obcca.NewECA() defer eca.Close() tca := obcca.NewTCA(eca) defer tca.Close() tlsca := obcca.NewTLSCA() defer tlsca.Close() var wg sync.WaitGroup eca.Start(&wg) tca.Start(&wg) tlsca.Start(&wg) wg.Wait() }
func init() { //Begin cobra configuration RootCommand.PersistentFlags().StringVarP(&server, "server", "s", "localhost", "Server to connect to, separate multiple servers with a \",\"") RootCommand.PersistentFlags().StringVarP(&keyspace, "keyspace", "k", "cassfs", "Keyspace to use for cassandra") RootCommand.PersistentFlags().StringVar(&statedir, "statedir", "/var/run/cassfs", "Directory to use for state") RootCommand.PersistentFlags().IntVarP(&owner, "owner", "o", 1, "Owner ID") RootCommand.PersistentFlags().StringVarP(&environment, "environment", "e", "production", "Environment to mount") RootCommand.PersistentFlags().Bool("debug", false, "Enable debugging") //Begin viper configuration viper.SetEnvPrefix("CASSFS") viper.AutomaticEnv() //End viper configuration //Read from a config file viper.SetConfigName("cassfs") viper.SetConfigType("yaml") viper.AddConfigPath("/etc/cassfs") viper.AddConfigPath("$HOME/.cassfs") viper.AddConfigPath(".") //Begin viper/cobra integration viper.BindPFlag("server", RootCommand.PersistentFlags().Lookup("server")) viper.BindPFlag("statedir", RootCommand.PersistentFlags().Lookup("statedir")) viper.BindPFlag("keyspace", RootCommand.PersistentFlags().Lookup("keyspace")) viper.BindPFlag("owner", RootCommand.PersistentFlags().Lookup("owner")) viper.BindPFlag("environment", RootCommand.PersistentFlags().Lookup("environment")) viper.BindPFlag("debug", RootCommand.PersistentFlags().Lookup("debug")) }
// InitializeConfig reads in config file and ENV variables if set. func InitializeConfig(subCmdVs ...*cobra.Command) error { viper.SetConfigType("json") viper.SetConfigName("grasshopper") // name of config file (without extension) // viper.AddConfigPath("/etc/grasshopper.d/") // path to look for the config file // viper.AddConfigPath("$HOME/.grasshopper.d") // call multiple times to add many search paths viper.AddConfigPath(".") // optionally look for config in the working directory // read config from storage err := viper.ReadInConfig() if err != nil { jww.WARN.Printf("Unable to read Config file. %#v I will fall back to my defaults...", err) err = nil // we just skip this error } // set some sane defaults viper.SetDefault("Verbose", false) viper.SetDefault("Quiet", false) viper.SetDefault("Log", true) viper.SetDefault("Experimental", true) if grasshopperCmdV.PersistentFlags().Lookup("verbose").Changed { viper.Set("Verbose", Verbose) } if viper.GetBool("verbose") { jww.SetStdoutThreshold(jww.LevelTrace) jww.SetLogThreshold(jww.LevelTrace) } return err }
func main() { var configDefault string = "chat" viper.SetConfigName(configDefault) viper.SetConfigType("toml") viper.AddConfigPath("./") viper.SetDefault(telnetIPWord, "127.0.0.1") viper.SetDefault(telnetPortWord, "6000") viper.SetDefault(apiIPWord, "127.0.0.1") viper.SetDefault(apiPortWord, "6001") err := viper.ReadInConfig() if err != nil { fmt.Printf("No configuration file found:%s:err:%v: - using defaults\n", configDefault, err) } logFile := viper.GetString("logFile") log.MustSetupLogging(logFile) log.Info("listening on:telnet:%s:%s:api:%s:%s:\n", viper.GetString(telnetIPWord), viper.GetString(telnetPortWord), viper.GetString(apiIPWord), viper.GetString(apiPortWord)) msgchan := make(chan m.ChatMsg) addchan := make(chan client.Client) rmchan := make(chan client.Client) go handleMessages(msgchan, addchan, rmchan) go telnet.TelnetServer(viper.GetString(telnetIPWord), viper.GetString(telnetPortWord), msgchan, addchan, rmchan) api.ApiServer(viper.GetString(apiIPWord), viper.GetString(apiPortWord), msgchan, addchan, rmchan) }
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 main() { viper.SetDefault("port", 3000) viper.SetDefault("udpBufSize", 1024) viper.SetConfigType("json") viper.SetConfigName("config") viper.AddConfigPath("./config") err := viper.ReadInConfig() if err != nil { log.Fatal("Config file ", err) } port := viper.GetString("port") udpAddr, err := net.ResolveUDPAddr("udp4", ":"+port) if err != nil { log.Fatal("Resolve udp addr ", err) } conn, err := net.ListenUDP("udp", udpAddr) if err != nil { log.Fatal(err) } log.Println("Server is starting on " + port) size := viper.GetInt("udpBufSize") client := handler.NewClient() for { buf := make([]byte, size) rlen, addr, err := conn.ReadFromUDP(buf) if err != nil { conn.WriteToUDP([]byte("error"), addr) } else { go client.Handle(conn, addr, rlen, buf) } } }
func LoadSettingsFromFile() { viper.SetConfigType(ConfigType) setConfigLocation() // Set defaults viper.SetDefault("Port", Port) viper.SetDefault("EnableAutomerge", EnableAutomerge) viper.SetDefault("Debug", Debug) viper.SetDefault("DefaultEnvironment", DefaultEnvironment) viper.SetDefault("DefaultTask", DefaultTask) viper.SetDefault("BoltdbName", BoltdbName) // Load configuration err := viper.ReadInConfig() if err != nil { log.Warning("Configuration not found, loading defaults") } // set log level if viper.GetBool("Debug") { log.SetLevel(log.DebugLevel) } else { log.SetLevel(log.InfoLevel) } log.Debugf("Loaded setting values: %v", viper.AllSettings()) log.Info("Settings loaded") }
func InitConfig() { viper.SetConfigName("scds") viper.SetConfigType("yaml") viper.SetEnvPrefix("scds") viper.AutomaticEnv() // Replaces underscores with periods when mapping environment variables. viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) // Set non-zero defaults. Nested options take a lower precedence than // dot-delimited ones, so namespaced options are defined here as maps. viper.SetDefault("mongo", map[string]interface{}{ "uri": "localhost/scds", }) viper.SetDefault("http", map[string]interface{}{ "host": "localhost", "port": 5000, }) viper.SetDefault("smtp", map[string]interface{}{ "host": "localhost", "port": 25, }) // Read the default config file from the working directory. dir, err := os.Getwd() if err != nil { log.Fatal(err) } viper.AddConfigPath(dir) }
func init() { viper.SetConfigType("yaml") viper.AutomaticEnv() envReplacer := strings.NewReplacer(".", "_") viper.SetEnvKeyReplacer(envReplacer) }
func main() { // config defaults viper.SetDefault("SigningKey", "change me in config/app.toml") viper.SetDefault("Port", "8888") viper.SetDefault("Database", "postgresql") viper.SetConfigType("toml") viper.SetConfigName("app") viper.AddConfigPath("./config/") // TODO better error message err := viper.ReadInConfig() if err != nil { fmt.Print(fmt.Errorf("Fatal error config file: %s \n", err)) fmt.Println("Config path is ./config/, and name should be app.toml") fmt.Println("Using defaults") } // TODO: check toml for nested propeties // TODO: Handle config in a separate module? file? dbConfig := viper.GetStringMap("Database") dbName := dbConfig["Name"] dbUser := dbConfig["User"] // fmt.Sprintf("user=%s dbname=%s sslmode=disable", dbUser, dbName) dbOptions := db.Options{ Driver: "postgres", Params: fmt.Sprintf("user=%s dbname=%s sslmode=disable", dbUser, dbName), } dbConnection := db.Connect(dbOptions) app := NewApp([]byte(viper.GetString("SigningKey")), dbConnection) port := viper.GetString("Port") log.Printf("Serving on port: %s\n", port) app.E.Run(":" + port) }
// initConfig reads in config file and ENV variables if set. func initConfig() { if cfgFile == "" { // enable ability to specify config file via flag cfgFile = filepath.Join(os.Getenv("HOME"), ".alea.toml") } viper.SetConfigFile(cfgFile) viper.SetConfigName(".alea") // name of config file (without extension) viper.SetConfigType("toml") // type of config file (defaults to yaml) viper.AddConfigPath("$HOME") // adding home directory as first search path viper.AutomaticEnv() // read in environment variables that match // bind flags viper.BindPFlag("controller", RootCmd.PersistentFlags().Lookup("controller")) // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { // fmt.Println("Using config file:", viper.ConfigFileUsed()) // Try to set the controller to the value found in the config if cfg.controller == "" { cfg.controller = viper.GetString("controller") } // Try to resolve the controller URL from the deis git remote if it's still blank if cfg.controller == "" { cfg.controller, err = git.GetControllerFromRemote() } } }
func persistentPreRun(cmd *cobra.Command, args []string) { // Viper requires a configuration "file" so we provide an empty one here. viper.SetConfigType("yaml") var yamlConfig = []byte("") viper.ReadConfig(bytes.NewBuffer(yamlConfig)) loadDefaultSettings() }
func InitConf(configFile string) { cfgData, err := ioutil.ReadFile(configFile) if err != nil { fmt.Println(err) } viper.SetConfigType("yaml") viper.ReadConfig(bytes.NewBuffer(cfgData)) }
func InitConfig() { viper.SetConfigFile("config") viper.SetConfigType("toml") viper.AddConfigPath(".") err := viper.ReadInConfig() if err != nil { log.Println(err) } }
func init() { logrus.SetLevel(logrus.ErrorLevel) logrus.SetOutput(os.Stderr) // Retrieve current user to get home directory usr, err := user.Current() if err != nil { fatalf("cannot get current user: %v", err) } // Get home directory for current user homeDir := usr.HomeDir if homeDir == "" { fatalf("cannot get current user home directory") } // Setup the configuration details viper.SetConfigName(configFileName) viper.AddConfigPath(path.Join(homeDir, path.Dir(configPath))) viper.SetConfigType("json") // Find and read the config file err = viper.ReadInConfig() if err != nil { // Ignore if the configuration file doesn't exist, we can use the defaults if !os.IsNotExist(err) { fatalf("fatal error config file: %v", err) } } // Set up the defaults for our config viper.SetDefault("trustDir", path.Join(homeDir, path.Dir(trustDir))) viper.SetDefault("privDir", path.Join(homeDir, path.Dir(privDir))) viper.SetDefault("tufDir", path.Join(homeDir, path.Dir(tufDir))) // Get the final value for the CA directory finalTrustDir := viper.GetString("trustDir") finalPrivDir := viper.GetString("privDir") // Load all CAs that aren't expired and don't use SHA1 // We could easily add "return cert.IsCA && cert.BasicConstraintsValid" in order // to have only valid CA certificates being loaded caStore, err = trustmanager.NewX509FilteredFileStore(finalTrustDir, func(cert *x509.Certificate) bool { return time.Now().Before(cert.NotAfter) && cert.SignatureAlgorithm != x509.SHA1WithRSA && cert.SignatureAlgorithm != x509.DSAWithSHA1 && cert.SignatureAlgorithm != x509.ECDSAWithSHA1 }) if err != nil { fatalf("could not create X509FileStore: %v", err) } privKeyStore, err = trustmanager.NewPrivateFileStore(finalPrivDir, "key") if err != nil { fatalf("could not create FileStore: %v", err) } }
// Loads the given yaml file as a Value. func LoadYaml(file string) *Source { y, err := ioutil.ReadFile(file) maybePanic(err) viper.SetConfigType("yaml") viper.ReadConfig(bytes.NewBuffer(y)) conf := viper.AllSettings() return NewSource(vals.New(conf)) }
func init() { viper.SetConfigName(ConfigFileName) viper.SetConfigType(ConfigFileType) viper.AddConfigPath(ConfigFilePath) err := viper.ReadInConfig() if err != nil { log.Debug(err) } }
// initConfig reads in config file and ENV variables if set. func initConfig() { configPath := constants.ConfigFile viper.SetConfigFile(configPath) viper.SetConfigType("json") err := viper.ReadInConfig() if err != nil { glog.Warningf("Error reading config file at %s: %s", configPath, err) } setupViper() }