// 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 init() { viper.SetEnvPrefix("vk") viper.BindEnv("token") viper.BindEnv("id") viper.BindEnv("mongo") viper.BindEnv("db") }
func init() { // default values // If no config is found, use the default(s) viper.SetDefault("port", 80) viper.SetDefault("crate_rest_api", "") viper.SetDefault("crate", false) // environment variable viper.SetEnvPrefix("fci") // will be uppercased automatically viper.BindEnv("port") viper.BindEnv("crate") viper.BindEnv("crate_rest_api") // config file viper.AddConfigPath("./") viper.SetConfigName("config") err := viper.ReadInConfig() // check if configfile is available if err != nil { fmt.Println("No configuration file loaded") // os.Exit(1) } }
func readConfig() { viper.SetEnvPrefix("chat") viper.SetDefault("database_url", "postgres:///chat_development?sslmode=disable") viper.SetDefault("bind_address", "localhost:8080") viper.AutomaticEnv() viper.BindEnv("database_url") viper.BindEnv("bind_address") }
func init() { viper.SetDefault("docroot", "/srv/docroot") viper.SetEnvPrefix("wodby") viper.BindEnv("app_type") viper.BindEnv("app_version") viper.BindEnv("environment_type") viper.BindEnv("environment_name") viper.BindEnv("namespace") }
func init() { viper.SetEnvPrefix("pdfgen") viper.BindEnv("port") viper.SetDefault("port", "8888") viper.BindEnv("addr") viper.SetDefault("addr", "0.0.0.0") viper.BindEnv("templates") viper.SetDefault("templates", "./templates") }
func init() { // set default log level to Error viper.SetDefault("logging", map[string]interface{}{"level": 2}) viper.SetEnvPrefix(_EnvPrefix) viper.BindEnv(_DefaultAliasEnv) viper.BindEnv(_PINCode) // Setup flags flag.StringVar(&configFile, "config", "", "Path to configuration file") flag.BoolVar(&debug, "debug", false, "show the version and exit") }
func setupEnvVars() { viper.SetEnvPrefix("mb") viper.BindEnv("env") viper.SetDefault("env", "development") viper.BindEnv("loglevel") viper.SetDefault("loglevel", "info") viper.BindEnv("host") viper.SetDefault("host", "localhost:7777") viper.BindEnv("redis_host") viper.SetDefault("redis_host", "localhost:6379") viper.BindEnv("redis_password") viper.SetDefault("redis_password", "") }
func init() { RootCmd.AddCommand(watchCmd) watchCmd.Flags().StringVarP(&hostedZone, "hosted-zone", "H", "", "Hosted zone to update") watchCmd.Flags().StringVarP(&checkID, "check-id", "C", "", "CheckID to use for IP output") watchCmd.Flags().StringSliceVarP(&domains, "domain", "D", []string{}, "Full domain name to keep global IPs") viper.SetEnvPrefix("collector") viper.BindEnv("hosted_zone") viper.BindEnv("check_id") viper.BindEnv("domain") cobra.OnInitialize(initEnviron) }
// TODO: Need to look at whether this is just too much going on. func init() { // enable ability to specify config file via flag RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.trackello.yaml)") if cfgFile != "" { viper.SetConfigFile(cfgFile) } viper.SetConfigName(".trackello") // name of config file (without extension) // Set Environment Variables viper.SetEnvPrefix("trackello") viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) // replace environment variables to underscore (_) from hyphen (-) if err := viper.BindEnv("appkey", trackello.TRACKELLO_APPKEY); err != nil { panic(err) } if err := viper.BindEnv("token", trackello.TRACKELLO_TOKEN); err != nil { panic(err) } if err := viper.BindEnv("board", trackello.TRACKELLO_PREFERRED_BOARD); err != nil { panic(err) } viper.AutomaticEnv() // read in environment variables that match every time Get() is called // Add Configuration Paths if cwd, err := os.Getwd(); err == nil { viper.AddConfigPath(cwd) } viper.AddConfigPath("$HOME") // adding home directory as first search path // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) } RootCmd.AddCommand(configCmd) RootCmd.PersistentFlags().StringVar(&trelloAppKey, "appkey", "", "Trello Application Key") if err := viper.BindPFlag("appkey", RootCmd.PersistentFlags().Lookup("appkey")); err != nil { panic(err) } RootCmd.PersistentFlags().StringVar(&trelloToken, "token", "", "Trello Token") if err := viper.BindPFlag("token", RootCmd.PersistentFlags().Lookup("token")); err != nil { panic(err) } RootCmd.PersistentFlags().StringVar(&preferredBoard, "board", "", "Preferred Board ID") if err := viper.BindPFlag("board", RootCmd.PersistentFlags().Lookup("board")); err != nil { panic(err) } viper.RegisterAlias("preferredBoard", "board") }
func passphraseRetriever(keyName, alias string, createNew bool, attempts int) (passphrase string, giveup bool, err error) { viper.BindEnv(alias) passphrase = viper.GetString(strings.ToUpper(alias)) if passphrase == "" { return "", false, errors.New("expected env variable to not be empty: " + alias) } return passphrase, false, nil }
func init() { viper.SetEnvPrefix("snake") viper.BindEnv("target") viper.SetConfigName("config") viper.AddConfigPath("/etc/snake/") viper.AddConfigPath("$HOME/.snake") viper.AddConfigPath(".") err := viper.ReadInConfig() // Find and read the config file if err != nil { // Handle errors reading the config file panic(fmt.Errorf("Fatal error config file: %s \n", err)) } }
func processVars() { flag.String("targetDirs", "", "Local directories to back up.") flag.String("s3Host", "", "S3 host.") flag.String("s3AccessKey", "", "S3 access key.") flag.String("s3SecretKey", "", "S3 secret key.") flag.String("s3BucketName", "", "S3 Bucket Name.") flag.Int("remoteWorkerCount", 5, "Number of workers performing actions against S3 host.") flag.Bool("dryRun", false, "Flag to indicate that this should be a dry run.") flag.Parse() viper.BindPFlag("targetDirs", flag.CommandLine.Lookup("targetDirs")) viper.BindPFlag("s3Host", flag.CommandLine.Lookup("s3Host")) viper.BindPFlag("s3AccessKey", flag.CommandLine.Lookup("s3AccessKey")) viper.BindPFlag("s3SecretKey", flag.CommandLine.Lookup("s3SecretKey")) viper.BindPFlag("s3BucketName", flag.CommandLine.Lookup("s3BucketName")) viper.BindPFlag("remoteWorkerCount", flag.CommandLine.Lookup("remoteWorkerCount")) viper.BindPFlag("dryRun", flag.CommandLine.Lookup("dryRun")) viper.AutomaticEnv() viper.SetEnvPrefix("PERSONAL_BACKUP") viper.BindEnv("targetDirs") viper.BindEnv("s3Host") viper.BindEnv("s3AccessKey") viper.BindEnv("s3SecretKey") viper.BindEnv("s3BucketName") viper.BindEnv("remoteWorkerCount") viper.SetDefault("remoteWorkerCount", 5) }
func main() { fmt.Printf("Version: %s\n", Version) // setup our settings viper.SetEnvPrefix("wmc") viper.BindEnv("serial") viper.SetDefault("serial", "/dev/ttyUSB0") var rootCmd = &cobra.Command{} rootCmd.AddCommand(cmdWmcVersion, cmdList, cmdPut, cmdRm, cmdConfig, cmdVersion) rootCmd.Execute() }
// InitializeConfig loads our configuration using Viper package. func InitializeConfig() { // Set config file viper.SetConfigName("config") // Add config path viper.AddConfigPath("$HOME/.sharptv") // Read in the config err := viper.ReadInConfig() // Find and read the config file if err != nil { // Handle errors reading the config file panic(fmt.Errorf("Fatal error config file: %s \n", err)) } // Load default settings viper.SetDefault("debug", false) viper.SetEnvPrefix("gosharptv") // will be uppercased automatically viper.BindEnv("debug") viper.BindEnv("ip") viper.BindEnv("port") // Do some flag handling and any complicated config logic if !viper.IsSet("ip") || !viper.IsSet("port") { fmt.Println("Configuration error. Both IP and PORT must be set via either config, environment, or flags.") os.Exit(1) } // TODO --implement the use of this data in the input command inputLabelMap = make(map[string]int) inputNames := []string{"input1", "input2", "input3", "input4", "input5", "input6", "input7", "input8"} for i, v := range inputNames { if viper.IsSet(v) { inputname := viper.GetString(v) inputLabelMap[inputname] = i + 1 } } }
func init() { flag.StringVar(&config, "config", "config", "config name [.toml,.json,.yml]") flag.StringVar(&configpath, "configpath", ".", "config location") flag.Parse() //env viper.BindEnv("SERVER_MONGO_1_PORT_27017_TCP_ADDR") //setup config viper.AddConfigPath(configpath) viper.AddConfigPath("/") viper.SetConfigName(config) viper.ReadInConfig() }
func initByEnv() { log.Println("init params by env..") viper.BindEnv("host", "HOST") viper.BindEnv("port", "PORT") viper.BindEnv("logLevel", "LOG_LEVEL") viper.BindEnv("cache.host", "CACHE_HOST") viper.BindEnv("cache.port", "CACHE_PORT") viper.BindEnv("cache.poolSize", "CACHE_POOLSIZE") }
func InitializeConfig() { viper.SetConfigName("authcurl") viper.SetEnvPrefix("auth") viper.AddConfigPath("$HOME/.authcurl") viper.AddConfigPath("$HOME/.config/authcurl") viper.AddConfigPath("$HOME/.config") viper.SetDefault("Region", "us-east-1") viper.SetDefault("allow_insecure_ssl", false) viper.SetDefault("service", "") viper.BindEnv("region") viper.BindEnv("secret_key") viper.BindEnv("access_key") if authCmdV.PersistentFlags().Lookup("region").Changed { viper.Set("Region", Region) } if authCmdV.PersistentFlags().Lookup("access-key").Changed { viper.Set("access_key", AccessKey) } if authCmdV.PersistentFlags().Lookup("secret-key").Changed { viper.Set("secret_key", SecretKey) } if authCmdV.PersistentFlags().Lookup("service").Changed { viper.Set("service", Service) } if authCmdV.PersistentFlags().Lookup("allow-insecure-ssl").Changed { viper.Set("allow_insecure_ssl", AllowInsecureSsl) } }
func initConfig() { viper.SetDefault("host", "localhost") viper.SetDefault("port", ":5090") viper.SetDefault("logLevel", "DEBUG") viper.SetDefault("watch", false) viper.SetDefault("cache.poolSize", 100) viper.BindEnv("init_model", "INIT_MODEL") model := viper.GetInt("init_model") switch model { case 0: initByConfigFile() case 1: initByEnv() default: initByConfigFile() } }
func main() { // setup our settings viper.SetEnvPrefix("wmc") viper.BindEnv("serial") viper.SetDefault("serial", "/dev/ttyUSB0") var rootCmd = &cobra.Command{ Use: "wmc", Short: "wmc is a cross-platform command line utility for the WifiMCU Platform", Long: `wmc: ` + Version + ` wmc is a cross-platform command line utility for the WifiMCU Platform GPL Licensed source code, downloads and issue tracker at https://github.com/zpeters/wmc`, } rootCmd.AddCommand(cmdWmcVersion, cmdList, cmdPut, cmdRm, cmdConfig, cmdCommand, cmdRead, cmdRun, cmdReboot) rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") rootCmd.Execute() }
// ResetSettings resets the viper settings func ResetSettings() { log.Debug("Resetting all the settings") viper.Reset() // We will use yaml settings viper.SetConfigType(configType) // Get the settigns file from env var viper.SetEnvPrefix("monf") viper.BindEnv(SettingsPath) // start App configuration // TODO: Specify settings file filePath := "" if SpecificConfigPath != "" { filePath = SpecificConfigPath } LoadSettings(filePath) }
func init() { viper.SetEnvPrefix("chaos") viper.BindEnv("env") viper.SetDefault("env", "development") viper.SetConfigName("config") viper.SetConfigType("toml") viper.AddConfigPath(".") viper.SetDefault("redis", map[string]interface{}{ "host": "localhost", "port": 6379, "db": 8, }) viper.SetDefault("http", map[string]interface{}{ "port": 8080, "domain": "localhost", "ssl": false, }) viper.SetDefault("database", map[string]interface{}{ "driver": "postgres", "args": map[string]interface{}{ "host": "localhost", "port": 5432, "user": "******", "dbname": "chaos", "sslmode": "disable", }, "pool": map[string]int{ "max_open": 180, "max_idle": 6, }, }) viper.SetDefault("secrets", RandomStr(512)) viper.SetDefault("workers.config", map[string]interface{}{ "pool": 30, "namespace": "tasks", "process": RandomStr(8), }) }
// initConfig reads in config file and ENV variables if set. func initConfig() { viper.SetConfigType("yaml") viper.SetConfigName(".ttn") // name of config file (without extension) viper.AddConfigPath("$HOME") // adding home directory as first search path viper.SetEnvPrefix("ttn") // set environment prefix viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_")) viper.AutomaticEnv() // read in environment variables that match if cfgFile != "" { // enable ability to specify config file via flag viper.SetConfigFile(cfgFile) } viper.BindEnv("debug") // If a config file is found, read it in. err := viper.ReadInConfig() if err != nil { fmt.Println("Error when reading config file:", err) os.Exit(1) } else if err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) } }
// Main runs Centrifugo as a service. func Main() { var port string var address string var debug bool var name string var web string var engn string var logLevel string var logFile string var insecure bool var useSSL bool var sslCert string var sslKey string var redisHost string var redisPort string var redisPassword string var redisDB string var redisURL string var redisAPI bool var redisPool int var rootCmd = &cobra.Command{ Use: "", Short: "Centrifugo", Long: "Centrifuge + GO = Centrifugo – harder, better, faster, stronger", Run: func(cmd *cobra.Command, args []string) { viper.SetDefault("gomaxprocs", 0) viper.SetDefault("prefix", "") viper.SetDefault("web_password", "") viper.SetDefault("web_secret", "") viper.RegisterAlias("cookie_secret", "web_secret") viper.SetDefault("max_channel_length", 255) viper.SetDefault("channel_prefix", "centrifugo") viper.SetDefault("node_ping_interval", 5) viper.SetDefault("message_send_timeout", 60) viper.SetDefault("expired_connection_close_delay", 10) viper.SetDefault("presence_ping_interval", 25) viper.SetDefault("presence_expire_interval", 60) viper.SetDefault("private_channel_prefix", "$") viper.SetDefault("namespace_channel_boundary", ":") viper.SetDefault("user_channel_boundary", "#") viper.SetDefault("user_channel_separator", ",") viper.SetDefault("client_channel_boundary", "&") viper.SetDefault("sockjs_url", "https://cdn.jsdelivr.net/sockjs/1.0/sockjs.min.js") viper.SetDefault("project_name", "") viper.SetDefault("project_secret", "") viper.SetDefault("project_connection_lifetime", false) viper.SetDefault("project_watch", false) viper.SetDefault("project_publish", false) viper.SetDefault("project_anonymous", false) viper.SetDefault("project_presence", false) viper.SetDefault("project_history_size", 0) viper.SetDefault("project_history_lifetime", 0) viper.SetDefault("project_namespaces", "") viper.SetEnvPrefix("centrifugo") viper.BindEnv("engine") viper.BindEnv("insecure") viper.BindEnv("web_password") viper.BindEnv("web_secret") viper.BindEnv("project_name") viper.BindEnv("project_secret") viper.BindEnv("project_connection_lifetime") viper.BindEnv("project_watch") viper.BindEnv("project_publish") viper.BindEnv("project_anonymous") viper.BindEnv("project_join_leave") viper.BindEnv("project_presence") viper.BindEnv("project_history_size") viper.BindEnv("project_history_lifetime") viper.BindPFlag("port", cmd.Flags().Lookup("port")) viper.BindPFlag("address", cmd.Flags().Lookup("address")) viper.BindPFlag("debug", cmd.Flags().Lookup("debug")) viper.BindPFlag("name", cmd.Flags().Lookup("name")) viper.BindPFlag("web", cmd.Flags().Lookup("web")) viper.BindPFlag("engine", cmd.Flags().Lookup("engine")) viper.BindPFlag("insecure", cmd.Flags().Lookup("insecure")) viper.BindPFlag("ssl", cmd.Flags().Lookup("ssl")) viper.BindPFlag("ssl_cert", cmd.Flags().Lookup("ssl_cert")) viper.BindPFlag("ssl_key", cmd.Flags().Lookup("ssl_key")) viper.BindPFlag("log_level", cmd.Flags().Lookup("log_level")) viper.BindPFlag("log_file", cmd.Flags().Lookup("log_file")) viper.BindPFlag("redis_host", cmd.Flags().Lookup("redis_host")) viper.BindPFlag("redis_port", cmd.Flags().Lookup("redis_port")) viper.BindPFlag("redis_password", cmd.Flags().Lookup("redis_password")) viper.BindPFlag("redis_db", cmd.Flags().Lookup("redis_db")) viper.BindPFlag("redis_url", cmd.Flags().Lookup("redis_url")) viper.BindPFlag("redis_api", cmd.Flags().Lookup("redis_api")) viper.BindPFlag("redis_pool", cmd.Flags().Lookup("redis_pool")) err := validateConfig(configFile) if err != nil { logger.FATAL.Fatalln(err) } viper.SetConfigFile(configFile) err = viper.ReadInConfig() if err != nil { logger.FATAL.Fatalln("unable to locate config file") } setupLogging() if os.Getenv("GOMAXPROCS") == "" { if viper.IsSet("gomaxprocs") && viper.GetInt("gomaxprocs") > 0 { runtime.GOMAXPROCS(viper.GetInt("gomaxprocs")) } else { runtime.GOMAXPROCS(runtime.NumCPU()) } } logger.INFO.Println("GOMAXPROCS set to", runtime.GOMAXPROCS(0)) logger.INFO.Println("using config file:", viper.ConfigFileUsed()) c := newConfig() s := structureFromConfig(nil) app, err := libcentrifugo.NewApplication(c) if err != nil { logger.FATAL.Fatalln(err) } app.SetStructure(s) var e libcentrifugo.Engine switch viper.GetString("engine") { case "memory": e = libcentrifugo.NewMemoryEngine(app) case "redis": e = libcentrifugo.NewRedisEngine( app, viper.GetString("redis_host"), viper.GetString("redis_port"), viper.GetString("redis_password"), viper.GetString("redis_db"), viper.GetString("redis_url"), viper.GetBool("redis_api"), viper.GetInt("redis_pool"), ) default: logger.FATAL.Fatalln("unknown engine: " + viper.GetString("engine")) } logger.INFO.Println("engine:", viper.GetString("engine")) logger.DEBUG.Printf("%v\n", viper.AllSettings()) logger.INFO.Println("Use SSL:", viper.GetBool("ssl")) if viper.GetBool("ssl") { if viper.GetString("ssl_cert") == "" { logger.FATAL.Println("No SSL certificate provided") os.Exit(1) } if viper.GetString("ssl_key") == "" { logger.FATAL.Println("No SSL certificate key provided") os.Exit(1) } } app.SetEngine(e) app.Run() go handleSignals(app) mux := libcentrifugo.DefaultMux(app, viper.GetString("prefix"), viper.GetString("web"), viper.GetString("sockjs_url")) addr := viper.GetString("address") + ":" + viper.GetString("port") logger.INFO.Printf("start serving on %s\n", addr) if useSSL { if err := http.ListenAndServeTLS(addr, sslCert, sslKey, mux); err != nil { logger.FATAL.Fatalln("ListenAndServe:", err) } } else { if err := http.ListenAndServe(addr, mux); err != nil { logger.FATAL.Fatalln("ListenAndServe:", err) } } }, } rootCmd.Flags().StringVarP(&port, "port", "p", "8000", "port to bind to") rootCmd.Flags().StringVarP(&address, "address", "a", "", "address to listen on") rootCmd.Flags().BoolVarP(&debug, "debug", "d", false, "debug mode - please, do not use it in production") rootCmd.Flags().StringVarP(&configFile, "config", "c", "config.json", "path to config file") rootCmd.Flags().StringVarP(&name, "name", "n", "", "unique node name") rootCmd.Flags().StringVarP(&web, "web", "w", "", "optional path to web interface application") rootCmd.Flags().StringVarP(&engn, "engine", "e", "memory", "engine to use: memory or redis") rootCmd.Flags().BoolVarP(&insecure, "insecure", "", false, "start in insecure mode") rootCmd.Flags().BoolVarP(&useSSL, "ssl", "", false, "accept SSL connections. This requires an X509 certificate and a key file") rootCmd.Flags().StringVarP(&sslCert, "ssl_cert", "", "", "path to an X509 certificate file") rootCmd.Flags().StringVarP(&sslKey, "ssl_key", "", "", "path to an X509 certificate key") rootCmd.Flags().StringVarP(&logLevel, "log_level", "", "info", "set the log level: debug, info, error, critical, fatal or none") rootCmd.Flags().StringVarP(&logFile, "log_file", "", "", "optional log file - if not specified all logs go to STDOUT") rootCmd.Flags().StringVarP(&redisHost, "redis_host", "", "127.0.0.1", "redis host (Redis engine)") rootCmd.Flags().StringVarP(&redisPort, "redis_port", "", "6379", "redis port (Redis engine)") rootCmd.Flags().StringVarP(&redisPassword, "redis_password", "", "", "redis auth password (Redis engine)") rootCmd.Flags().StringVarP(&redisDB, "redis_db", "", "0", "redis database (Redis engine)") rootCmd.Flags().StringVarP(&redisURL, "redis_url", "", "", "redis connection URL (Redis engine)") rootCmd.Flags().BoolVarP(&redisAPI, "redis_api", "", false, "enable Redis API listener (Redis engine)") rootCmd.Flags().IntVarP(&redisPool, "redis_pool", "", 256, "Redis pool size (Redis engine)") var versionCmd = &cobra.Command{ Use: "version", Short: "Centrifugo version number", Long: `Print the version number of Centrifugo`, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Centrifugo v%s\n", VERSION) }, } var checkConfigFile string var checkConfigCmd = &cobra.Command{ Use: "checkconfig", Short: "Check configuration file", Long: `Check Centrifugo configuration file`, Run: func(cmd *cobra.Command, args []string) { err := validateConfig(checkConfigFile) if err != nil { logger.FATAL.Fatalln(err) } }, } checkConfigCmd.Flags().StringVarP(&checkConfigFile, "config", "c", "config.json", "path to config file to check") var outputConfigFile string var generateConfigCmd = &cobra.Command{ Use: "genconfig", Short: "Generate simple configuration file to start with", Long: `Generate simple configuration file to start with`, Run: func(cmd *cobra.Command, args []string) { err := generateConfig(outputConfigFile) if err != nil { logger.FATAL.Fatalln(err) } }, } generateConfigCmd.Flags().StringVarP(&outputConfigFile, "config", "c", "config.json", "path to output config file") rootCmd.AddCommand(versionCmd) rootCmd.AddCommand(checkConfigCmd) rootCmd.AddCommand(generateConfigCmd) rootCmd.Execute() }
// NewContext created new context for settings func NewContext(c *cobra.Command) { repl := strings.NewReplacer(".", "_") viper.SetEnvPrefix("kanban") viper.SetEnvKeyReplacer(repl) viper.SetDefault("server.listen", "0.0.0.0:80") viper.BindEnv("server.listen") if c.Flags().Lookup("server-listen").Changed { viper.BindPFlag("server.listen", c.Flags().Lookup("server-listen")) } viper.SetDefault("server.hostname", "http://localhost") viper.BindEnv("server.hostname") if c.Flags().Lookup("server-hostname").Changed { viper.BindPFlag("server.hostname", c.Flags().Lookup("server-hostname")) } viper.SetDefault("security.secret", "qwerty") viper.BindEnv("security.secret") if c.Flags().Lookup("security-secret").Changed { viper.BindPFlag("security.secret", c.Flags().Lookup("security-secret")) } viper.SetDefault("gitlab.url", "https://gitlab.com") viper.BindEnv("gitlab.url") if c.Flags().Lookup("gitlab-url").Changed { viper.BindPFlag("gitlab.url", c.Flags().Lookup("gitlab-url")) } viper.SetDefault("gitlab.client", "qwerty") viper.BindEnv("gitlab.client") if c.Flags().Lookup("gitlab-client").Changed { viper.BindPFlag("gitlab.client", c.Flags().Lookup("gitlab-client")) } viper.SetDefault("gitlab.secret", "qwerty") viper.BindEnv("gitlab.secret") if c.Flags().Lookup("gitlab-secret").Changed { viper.BindPFlag("gitlab.secret", c.Flags().Lookup("gitlab-secret")) } viper.SetDefault("redis.addr", "127.0.0.1:6379") viper.BindEnv("redis.addr") if c.Flags().Lookup("redis-addr").Changed { viper.BindPFlag("redis.addr", c.Flags().Lookup("redis-addr")) } viper.SetDefault("redis.password", "") viper.BindEnv("redis.password") if c.Flags().Lookup("redis-password").Changed { viper.BindPFlag("redis.password", c.Flags().Lookup("redis-password")) } viper.SetDefault("redis.db", 0) viper.BindEnv("redis.db") if c.Flags().Lookup("redis-db").Changed { viper.BindPFlag("redis.db", c.Flags().Lookup("redis-db")) } viper.SetDefault("version", "1.4.1") }
func init() { viper.SetDefault("port", 8000) viper.SetDefault("autopump", false) viper.BindEnv("port", "PORT") viper.BindEnv("autopump", "AUTOPUMP") viper.BindEnv("db-url", "DATABASE_URL") viper.BindEnv("stellar-core-db-url", "STELLAR_CORE_DATABASE_URL") viper.BindEnv("stellar-core-url", "STELLAR_CORE_URL") viper.BindEnv("friendbot-secret", "FRIENDBOT_SECRET") viper.BindEnv("per-hour-rate-limit", "PER_HOUR_RATE_LIMIT") viper.BindEnv("redis-url", "REDIS_URL") viper.BindEnv("ruby-horizon-url", "RUBY_HORIZON_URL") viper.BindEnv("log-level", "LOG_LEVEL") viper.BindEnv("sentry-dsn", "SENTRY_DSN") viper.BindEnv("loggly-token", "LOGGLY_TOKEN") viper.BindEnv("loggly-host", "LOGGLY_HOST") rootCmd = &cobra.Command{ Use: "horizon", Short: "client-facing api server for the stellar network", Long: "client-facing api server for the stellar network", Run: run, } rootCmd.Flags().String( "db-url", "", "horizon postgres database to connect with", ) rootCmd.Flags().String( "stellar-core-db-url", "", "stellar-core postgres database to connect with", ) rootCmd.Flags().String( "stellar-core-url", "", "stellar-core to connect with (for http commands)", ) rootCmd.Flags().Int( "port", 8000, "tcp port to listen on for http requests", ) rootCmd.Flags().Bool( "autopump", false, "pump streams every second, instead of once per ledger close", ) rootCmd.Flags().Int( "per-hour-rate-limit", 3600, "max count of requests allowed in a one hour period, by remote ip address", ) rootCmd.Flags().String( "redis-url", "", "redis to connect with, for rate limiting", ) rootCmd.Flags().String( "ruby-horizon-url", "", "proxy yet-to-be-implemented actions through to ruby horizon server", ) rootCmd.Flags().String( "log-level", "info", "Minimum log severity (debug, info, warn, error) to log", ) rootCmd.Flags().String( "sentry-dsn", "", "Sentry URL to which panics and errors should be reported", ) rootCmd.Flags().String( "loggly-token", "", "Loggly token, used to configure log forwarding to loggly", ) rootCmd.Flags().String( "loggly-host", "", "Hostname to be added to every loggly log event", ) rootCmd.Flags().String( "friendbot-secret", "", "Secret seed for friendbot functionality. When empty, friendbot will be disabled", ) viper.BindPFlags(rootCmd.Flags()) }
func init() { viper.SetDefault("port", 8000) viper.SetDefault("autopump", false) viper.BindEnv("port", "PORT") viper.BindEnv("autopump", "AUTOPUMP") viper.BindEnv("db-url", "DATABASE_URL") viper.BindEnv("stellar-core-db-url", "STELLAR_CORE_DATABASE_URL") viper.BindEnv("stellar-core-url", "STELLAR_CORE_URL") viper.BindEnv("friendbot-secret", "FRIENDBOT_SECRET") viper.BindEnv("per-hour-rate-limit", "PER_HOUR_RATE_LIMIT") viper.BindEnv("redis-url", "REDIS_URL") viper.BindEnv("ruby-horizon-url", "RUBY_HORIZON_URL") viper.BindEnv("log-level", "LOG_LEVEL") viper.BindEnv("sentry-dsn", "SENTRY_DSN") viper.BindEnv("loggly-token", "LOGGLY_TOKEN") viper.BindEnv("loggly-host", "LOGGLY_HOST") viper.BindEnv("tls-cert", "TLS_CERT") viper.BindEnv("tls-key", "TLS_KEY") viper.BindEnv("ingest", "INGEST") viper.BindEnv("network-passphrase", "NETWORK_PASSPHRASE") rootCmd = &cobra.Command{ Use: "horizon", Short: "client-facing api server for the stellar network", Long: "client-facing api server for the stellar network", Run: func(cmd *cobra.Command, args []string) { initApp(cmd, args) app.Serve() }, } rootCmd.Flags().String( "db-url", "", "horizon postgres database to connect with", ) rootCmd.Flags().String( "stellar-core-db-url", "", "stellar-core postgres database to connect with", ) rootCmd.Flags().String( "stellar-core-url", "", "stellar-core to connect with (for http commands)", ) rootCmd.Flags().Int( "port", 8000, "tcp port to listen on for http requests", ) rootCmd.Flags().Bool( "autopump", false, "pump streams every second, instead of once per ledger close", ) rootCmd.Flags().Int( "per-hour-rate-limit", 3600, "max count of requests allowed in a one hour period, by remote ip address", ) rootCmd.Flags().String( "redis-url", "", "redis to connect with, for rate limiting", ) rootCmd.Flags().String( "log-level", "info", "Minimum log severity (debug, info, warn, error) to log", ) rootCmd.Flags().String( "sentry-dsn", "", "Sentry URL to which panics and errors should be reported", ) rootCmd.Flags().String( "loggly-token", "", "Loggly token, used to configure log forwarding to loggly", ) rootCmd.Flags().String( "loggly-host", "", "Hostname to be added to every loggly log event", ) rootCmd.Flags().String( "friendbot-secret", "", "Secret seed for friendbot functionality. When empty, friendbot will be disabled", ) rootCmd.Flags().String( "tls-cert", "", "The TLS certificate file to use for securing connections to horizon", ) rootCmd.Flags().String( "tls-key", "", "The TLS private key file to use for securing connections to horizon", ) rootCmd.Flags().Bool( "ingest", false, "causes this horizon process to ingest data from stellar-core into horizon's db", ) rootCmd.Flags().String( "network-passphrase", "", "Override the network passphrase", ) rootCmd.AddCommand(dbCmd) viper.BindPFlags(rootCmd.Flags()) }
// NewConfig loads configuration from etcd and returns *Config struct // It also starts a goroutine in the background to keep config up-to-date func NewConfig() *Config { if configLoaded { return cnf } // Bind etcd env vars viper.SetDefault("etcd_host", "localhost") viper.SetDefault("etcd_port", "2379") viper.BindEnv("etcd_host") viper.BindEnv("etcd_port") // Construct the ETCD URL etcdURL := fmt.Sprintf( "http://%s:%s", viper.Get("etcd_host"), viper.Get("etcd_port"), ) // Config path configPath := "/config/go_oauth2_server.json" // Add a new ETCD remote provider runtimeViper := viper.New() runtimeViper.AddRemoteProvider("etcd", etcdURL, configPath) // Because there is no file extension in a stream of bytes runtimeViper.SetConfigType("json") // Read from remote config the first time. if err := runtimeViper.ReadRemoteConfig(); err != nil { log.Printf( "Unable to read remote config for the first time from %s/v2/keys%s: %v", etcdURL, configPath, err, ) } else { runtimeViper.Unmarshal(&cnf) } // Open a goroutine to watch remote changes forever go func() { for { // Delay after each request time.Sleep(time.Second * 5) if err := runtimeViper.WatchRemoteConfig(); err != nil { log.Printf( "Unable to read remote config from %s/v2/keys%s: %v", etcdURL, configPath, err, ) continue } // Unmarshal config runtimeViper.Unmarshal(&cnf) } }() configLoaded = true return cnf }
func initConfig(cmd *cobra.Command, suffix string, checkValues bool, flags map[string]FlagValue) { InitConfig() defaultFlags := map[string]FlagValue{} if len(flags) == 0 { defaultFlags = map[string]FlagValue{ // "username": {&username, true, false, ""}, // "password": {&password, true, false, ""}, // "endpoint": {&endpoint, true, false, ""}, // "insecure": {&insecure, false, false, ""}, } } for key, field := range flags { defaultFlags[key] = field } var fieldsMissing []string var fieldsMissingRemove []string type statusFlag struct { key string flagValue string flagValueExists bool flagChanged bool keyOverrideBy string flagValueOverrideBy string flagValueOverrideByExists bool flagChangedOverrideBy bool viperValue string viperValueExists bool viperValueOverrideBy string viperValueOverrideByExists bool gobValue string gobValueExists bool finalViperValue string setFrom string } cmdFlags := &pflag.FlagSet{} var statusFlags []statusFlag for key, field := range defaultFlags { viper.BindEnv(key) switch field.persistent { case true: cmdFlags = cmd.PersistentFlags() case false: cmdFlags = cmd.Flags() default: } var flagLookupValue string var flagLookupChanged bool if cmdFlags.Lookup(key) != nil { flagLookupValue = cmdFlags.Lookup(key).Value.String() flagLookupChanged = cmdFlags.Lookup(key).Changed } statusFlag := &statusFlag{ key: key, flagValue: flagLookupValue, flagChanged: flagLookupChanged, viperValue: viper.GetString(key), viperValueOverrideBy: viper.GetString(field.overrideby), } if statusFlag.flagValue != "" { statusFlag.flagValueExists = true } if statusFlag.flagValueOverrideBy != "" { statusFlag.flagValueOverrideByExists = true } if statusFlag.viperValue != "" { statusFlag.viperValueExists = true } if statusFlag.viperValueOverrideBy != "" { statusFlag.viperValueOverrideByExists = true } if field.overrideby != "" { statusFlag.keyOverrideBy = field.overrideby if cmdFlags.Lookup(field.overrideby) != nil { statusFlag.flagChangedOverrideBy = cmdFlags.Lookup(field.overrideby).Changed statusFlag.flagValueOverrideBy = cmdFlags.Lookup(field.overrideby).Value.String() } } statusFlags = append(statusFlags, *statusFlag) if err := setGobValues(cmd, suffix, key); err != nil { log.Fatal(err) } } for i := range statusFlags { statusFlags[i].setFrom = "none" statusFlags[i].gobValue = viper.GetString(statusFlags[i].key) if statusFlags[i].gobValue != "" { statusFlags[i].gobValueExists = true statusFlags[i].setFrom = "gob" } if statusFlags[i].gobValue == statusFlags[i].viperValue { if statusFlags[i].gobValueExists { statusFlags[i].setFrom = "ConfigOrEnv" } else { statusFlags[i].setFrom = "none" } } if statusFlags[i].flagValueOverrideByExists { viper.Set(statusFlags[i].key, "") statusFlags[i].setFrom = "flagValueOverrideByExists" continue } if statusFlags[i].flagValueExists { viper.Set(statusFlags[i].key, statusFlags[i].flagValue) statusFlags[i].setFrom = "flagValueExists" continue } if statusFlags[i].viperValueOverrideByExists { viper.Set(statusFlags[i].key, "") statusFlags[i].setFrom = "viperValueOverrideByExists" continue } } for _, statusFlag := range statusFlags { statusFlag.finalViperValue = viper.GetString(statusFlag.key) if os.Getenv("REXRAY_SHOW_FLAG") == "true" { fmt.Printf("%+v\n", statusFlag) } } if checkValues { for key, field := range defaultFlags { if field.mandatory == true { if viper.GetString(key) != "" && (field.overrideby != "" && viper.GetString(field.overrideby) == "") { fieldsMissingRemove = append(fieldsMissingRemove, field.overrideby) } else { //if viper.GetString(key) == "" && (field.overrideby != "" && viper.GetString(field.overrideby) == "") { if viper.GetString(key) == "" { fieldsMissing = append(fieldsMissing, key) } } } } for _, fieldMissingRemove := range fieldsMissingRemove { Loop1: for i, fieldMissing := range fieldsMissing { if fieldMissing == fieldMissingRemove { fieldsMissing = append(fieldsMissing[:i], fieldsMissing[i+1:]...) break Loop1 } } } if len(fieldsMissing) != 0 { log.Fatalf("missing parameter: %v", strings.Join(fieldsMissing, ", ")) } } for key := range defaultFlags { if viper.GetString(key) != "" { os.Setenv(fmt.Sprintf("REXRAY_%v", strings.ToUpper(key)), viper.GetString(key)) } //fmt.Println(viper.GetString(key)) } }
func initFlags() { viper.SetEnvPrefix("DIGITALOCEAN") viper.BindEnv("access-token", "DIGITALOCEAN_ACCESS_TOKEN") viper.BindPFlag("access-token", DoitCmd.PersistentFlags().Lookup("access-token")) viper.BindPFlag("output", DoitCmd.PersistentFlags().Lookup("output")) }