示例#1
2
// 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)
}
示例#2
1
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()
}
示例#3
1
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
}
示例#4
0
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()
}
示例#5
0
func main() {
	viper.SetEnvPrefix("SENSOR")
	viper.SetDefault("listen_address", ss.DefaultRadWSAddr)
	viper.SetDefault("flare_address", "localhost"+ss.DefaultFlareWSAddr)
	viper.AutomaticEnv()

	rand.Seed(time.Now().UTC().UnixNano())
	reading := &types.RadiationReading{
		Radiation: ss.InitRadiation,
	}

	flareExit := make(chan bool)
	flareAddr := viper.GetString("flare_address")
	go types.FlareUpdateRoutine(reading, &flareAddr, flareExit)

	go radiationRoutine(reading)

	addr := viper.GetString("listen_address")
	blaster := wsblaster.GetBlaster(&addr, false)
	go blaster.Run()
	ticker := time.NewTicker(1 * time.Second)
	for {
		select {
		case <-ticker.C:
			reading.RLock()
			m, _ := json.Marshal(reading)
			reading.RUnlock()
			blaster.Write(m)
		case <-flareExit:
			log.Fatal("Unable to connect to Solar Flare source")
		}
	}
}
示例#6
0
// 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(".gogetgithubstats") // name of config file (without extension)
	viper.AddConfigPath("$HOME")             // adding home directory as first search path
	viper.AutomaticEnv()                     // read in environment variables that match

	// This is the defaults
	viper.SetDefault("Verbose", true)

	// If a config file is found, read it in.
	err := viper.ReadInConfig()
	if err != nil {
		if _, ok := err.(viper.ConfigParseError); ok {
			jww.ERROR.Println(err)
		} else {
			jww.ERROR.Println("Unable to locate Config file.", err)
		}
	}

	if rootCmdV.PersistentFlags().Lookup("verbose").Changed {
		viper.Set("Verbose", Verbose)
	}

	if rootCmdV.PersistentFlags().Lookup("access-token").Changed {
		viper.Set("access-token", accessToken)
	}

	if viper.GetBool("verbose") {
		jww.SetStdoutThreshold(jww.LevelDebug)
	}
}
示例#7
0
文件: root.go 项目: lursu/skelly
// 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)
	}
}
示例#8
0
// 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
}
示例#9
0
// Start entry point for chaincodes bootstrap.
func Start(cc Chaincode) error {
	viper.SetEnvPrefix("CORE")
	viper.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(replacer)

	flag.StringVar(&peerAddress, "peer.address", "", "peer address")

	flag.Parse()

	chaincodeLogger.Debug("Peer address: %s", getPeerAddress())

	// Establish connection with validating peer
	clientConn, err := newPeerClientConnection()
	if err != nil {
		chaincodeLogger.Error(fmt.Sprintf("Error trying to connect to local peer: %s", err))
		return fmt.Errorf("Error trying to connect to local peer: %s", err)
	}

	chaincodeLogger.Debug("os.Args returns: %s", os.Args)

	chaincodeSupportClient := pb.NewChaincodeSupportClient(clientConn)

	// Establish stream with validating peer
	stream, err := chaincodeSupportClient.Register(context.Background())
	if err != nil {
		return fmt.Errorf("Error chatting with leader at address=%s:  %s", getPeerAddress(), err)
	}

	chaincodename := viper.GetString("chaincode.id.name")
	err = chatWithPeer(chaincodename, stream, cc)

	return err
}
示例#10
0
文件: service.go 项目: romana/core
// 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
}
示例#11
0
// 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()
		}
	}
}
示例#12
0
文件: root.go 项目: mfojtik/dev-tools
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if len(cfgFile) != 0 {
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".otp-config")
	viper.AddConfigPath("$HOME")
	viper.AutomaticEnv()

	apiKey, _ := RootCmd.Flags().GetString("api-key")
	if len(apiKey) == 0 && len(os.Getenv("GITHUB_API_KEY")) > 0 {
		RootCmd.Flags().Set("api-key", os.Getenv("GITHUB_API_KEY"))
	}
	if len(apiKey) > 0 {
		if err := os.Setenv("GITHUB_API_KEY", apiKey); err != nil {
			fmt.Fprintf(os.Stderr, "Error: Unable to set GITHUB_API_KEY\n")
			os.Exit(1)
		}
	}

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}

	log.SetFormatter(&log.TextFormatter{})
	log.SetOutput(os.Stderr)
	if api.Verbose {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(log.WarnLevel)
	}
}
示例#13
0
文件: root.go 项目: cgt212/cassfs
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"))
}
示例#14
0
func main() {
	viper.SetEnvPrefix("SENSOR")
	viper.SetDefault("listen_address", ss.DefaultPubWSAddr)
	viper.SetDefault("temperature_address", "localhost"+ss.DefaultTempWSAddr)
	viper.SetDefault("radiation_address", "localhost"+ss.DefaultRadWSAddr)
	viper.SetDefault("aggregator_address", "localhost"+ss.DefaultAggWSAddr)
	viper.AutomaticEnv()

	reading := &types.SensorSuiteReading{}

	sensorExit := make(chan bool)
	go sensorUpdateRoutine(reading, sensorExit)

	publishExit := make(chan bool)
	go publishData(reading, publishExit)

	for {
		select {
		case <-sensorExit:
			log.Fatal("Unable to connect to one or more sensors")
		case <-publishExit:
			log.Fatal("Unrecoverable error writing to aggregator")
		}
	}
}
示例#15
0
// Start entry point for chaincodes bootstrap.
func Start(cc Chaincode) error {
	viper.SetEnvPrefix("OPENCHAIN")
	viper.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(replacer)
	/*
		viper.SetConfigName("openchain") // name of config file (without extension)
		viper.AddConfigPath("./../../../")        // path to look for the config file in
		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))
		}
	*/
	fmt.Printf("peer.address: %s\n", getPeerAddress())

	// Establish connection with validating peer
	clientConn, err := newPeerClientConnection()
	if err != nil {
		return fmt.Errorf("Error trying to connect to local peer: %s", err)
	}

	fmt.Printf("os.Args returns: %s\n", os.Args)

	chaincodeSupportClient := pb.NewChaincodeSupportClient(clientConn)

	//err = c.Run(chaincodeSupportClient)
	//if err != nil {
	//}
	// Handle message exchange with validating peer
	err = chatWithPeer(chaincodeSupportClient, cc)

	return err
}
示例#16
0
文件: config.go 项目: tubo028/hugo
// LoadGlobalConfig loads Hugo configuration into the global Viper.
func LoadGlobalConfig(relativeSourcePath, configFilename string) error {

	if relativeSourcePath == "" {
		relativeSourcePath = "."
	}

	viper.AutomaticEnv()
	viper.SetEnvPrefix("hugo")
	viper.SetConfigFile(configFilename)
	// See https://github.com/spf13/viper/issues/73#issuecomment-126970794
	if relativeSourcePath == "" {
		viper.AddConfigPath(".")
	} else {
		viper.AddConfigPath(relativeSourcePath)
	}
	err := viper.ReadInConfig()
	if err != nil {
		if _, ok := err.(viper.ConfigParseError); ok {
			return err
		}
		return fmt.Errorf("Unable to locate Config file. Perhaps you need to create a new site.\n       Run `hugo help new` for details. (%s)\n", err)
	}

	viper.RegisterAlias("indexes", "taxonomies")

	loadDefaultSettings()

	return nil
}
示例#17
0
文件: root.go 项目: tahitianstud/ata
// 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(".ata")  // 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.Println("Using config file:", viper.ConfigFileUsed())
	}

	// deal with verbose and debug mode
	if DebugMode {
		logger.SetLevel(logging.DebugLevel)
	}
	logger.ActivateVerboseOutput(VerboseMode)

	// check that work directory exists
	if !io.DirectoryExists(WorkDirectory) {
		log.Fatalf("Work directory '%s' does not exist or is not readable", WorkDirectory)
	}
}
示例#18
0
// Start entry point for chaincodes bootstrap.
func Start(cc Chaincode) error {
	viper.SetEnvPrefix("OPENCHAIN")
	viper.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(replacer)

	flag.StringVar(&peerAddress, "peer.address", "", "peer address")

	flag.Parse()

	chaincodeLogger.Debug("Peer address: %s", getPeerAddress())

	// Establish connection with validating peer
	clientConn, err := newPeerClientConnection()
	if err != nil {
		chaincodeLogger.Error(fmt.Sprintf("Error trying to connect to local peer: %s", err))
		return fmt.Errorf("Error trying to connect to local peer: %s", err)
	}

	chaincodeLogger.Debug("os.Args returns: %s", os.Args)

	chaincodeSupportClient := pb.NewChaincodeSupportClient(clientConn)

	err = chatWithPeer(chaincodeSupportClient, cc)

	return err
}
示例#19
0
文件: config.go 项目: chop-dbhi/scds
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)
}
示例#20
0
文件: grnl.go 项目: jzorn/grnl
// 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(".grnl") // 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("Error using config file %q\n%q", viper.ConfigFileUsed(), err)
	}

	if db != "" {
		viper.Set("db", db)
	}

	if editor != "" {
		viper.Set("editor", editor)
	}

	if dateFormat != "" {
		viper.Set("dateFormat", dateFormat)
	}
}
示例#21
0
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)
}
示例#22
0
文件: config.go 项目: ricobl/beat
func init() {
	viper.SetConfigType("yaml")
	viper.AutomaticEnv()

	envReplacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(envReplacer)
}
示例#23
0
func initViper() error {
	var err error

	viper.SetConfigName("sqlboiler")

	configHome := os.Getenv("XDG_CONFIG_HOME")
	homePath := os.Getenv("HOME")
	wd, err := os.Getwd()
	if err != nil {
		wd = "../"
	} else {
		wd = wd + "/.."
	}

	configPaths := []string{wd}
	if len(configHome) > 0 {
		configPaths = append(configPaths, filepath.Join(configHome, "sqlboiler"))
	} else {
		configPaths = append(configPaths, filepath.Join(homePath, ".config/sqlboiler"))
	}

	for _, p := range configPaths {
		viper.AddConfigPath(p)
	}

	// Ignore errors here, fall back to defaults and validation to provide errs
	_ = viper.ReadInConfig()
	viper.AutomaticEnv()

	return nil
}
示例#24
0
func main() {
	viper.SetEnvPrefix("SENSOR")
	viper.SetDefault("listen_address", ss.DefaultFlareWSAddr)
	viper.AutomaticEnv()

	rand.Seed(time.Now().UTC().UnixNano())
	reading := &types.FlareReading{
		SolarFlare: ss.InitSolarFlare,
	}

	go solarFlareRoutine(reading)

	addr := viper.GetString("listen_address")
	blaster := wsblaster.GetBlaster(&addr, false)
	go blaster.Run()
	ticker := time.NewTicker(1 * time.Second)
	for {
		select {
		case <-ticker.C:
			reading.RLock()
			m, _ := json.Marshal(reading)
			reading.RUnlock()
			blaster.Write(m)
		}
	}
}
示例#25
0
文件: main.go 项目: glycerine/origins
func main() {
	mainCmd.AddCommand(versionCmd)
	mainCmd.AddCommand(generateCmd)
	mainCmd.AddCommand(transactCmd)
	mainCmd.AddCommand(logCmd)
	mainCmd.AddCommand(httpCmd)
	mainCmd.AddCommand(domainsCmd)

	viper.SetEnvPrefix("ORIGINS")
	viper.AutomaticEnv()

	// Default locations for the origins config file.
	viper.SetConfigName("origins")

	// Directory the program is being called from
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))

	if err == nil {
		viper.AddConfigPath(dir)
	}

	flags := mainCmd.PersistentFlags()

	flags.String("log", "info", "Level of log messages to emit. Choices are: debug, info, warn, error, fatal, panic.")
	flags.String("config", "", "Path to config file. Defaults to a origins.{json,yml,yaml} in the current working directory.")

	viper.BindPFlag("log", flags.Lookup("log"))
	viper.BindPFlag("config", flags.Lookup("config"))

	// If the target subcommand is generate, remove the generator
	// arguments to prevent flag parsing errors.
	args := parseGenerateArgs(os.Args[1:])

	// Set explicit arguments and parse the flags to setup
	// the config file and logging.
	mainCmd.SetArgs(args)
	mainCmd.ParseFlags(args)

	config := viper.GetString("config")

	if config != "" {
		viper.SetConfigFile(config)
	}

	// Read configuration file if present.
	viper.ReadInConfig()

	// Turn on debugging for all commands.
	level, err := logrus.ParseLevel(viper.GetString("log"))

	if err != nil {
		fmt.Println("Invalid log level choice.")
		mainCmd.Help()
	}

	logrus.SetLevel(level)

	mainCmd.Execute()
}
示例#26
0
func setupViper() {
	viper.SetEnvPrefix(constants.MiniShiftEnvPrefix)
	viper.AutomaticEnv()

	viper.SetDefault(config.WantUpdateNotification, true)
	viper.SetDefault(config.ReminderWaitPeriodInHours, 24)
	setFlagsUsingViper()
}
示例#27
0
func init() {
	viper.SetConfigName("dkron")        // name of config file (without extension)
	viper.AddConfigPath("/etc/dkron")   // call multiple times to add many search paths
	viper.AddConfigPath("$HOME/.dkron") // call multiple times to add many search paths
	viper.AddConfigPath("./config")     // call multiple times to add many search paths
	viper.SetEnvPrefix("dkron")         // will be uppercased automatically
	viper.AutomaticEnv()
}
示例#28
0
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")
}
示例#29
0
文件: main.go 项目: yoshiharay/fabric
func main() {
	// For environment variables.
	viper.SetEnvPrefix(cmdRoot)
	viper.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(replacer)

	// Define command-line flags that are valid for all peer commands and
	// subcommands.
	mainFlags := mainCmd.PersistentFlags()
	mainFlags.BoolVarP(&versionFlag, "version", "v", false, "Display current version of fabric peer server")

	mainFlags.String("logging-level", "", "Default logging level and overrides, see core.yaml for full syntax")
	viper.BindPFlag("logging_level", mainFlags.Lookup("logging-level"))
	testCoverProfile := ""
	mainFlags.StringVarP(&testCoverProfile, "test.coverprofile", "", "coverage.cov", "Done")

	var alternativeCfgPath = os.Getenv("PEER_CFG_PATH")
	if alternativeCfgPath != "" {
		logger.Infof("User defined config file path: %s", alternativeCfgPath)
		viper.AddConfigPath(alternativeCfgPath) // Path to look for the config file in
	} else {
		viper.AddConfigPath("./") // Path to look for the config file in
		// Path to look for the config file in based on GOPATH
		gopath := os.Getenv("GOPATH")
		for _, p := range filepath.SplitList(gopath) {
			peerpath := filepath.Join(p, "src/github.com/hyperledger/fabric/peer")
			viper.AddConfigPath(peerpath)
		}
	}

	// Now set the configuration file.
	viper.SetConfigName(cmdRoot) // Name of config file (without extension)

	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error when reading %s config file: %s\n", cmdRoot, err))
	}

	mainCmd.AddCommand(version.Cmd())
	mainCmd.AddCommand(node.Cmd())
	mainCmd.AddCommand(network.Cmd())
	mainCmd.AddCommand(chaincode.Cmd())

	runtime.GOMAXPROCS(viper.GetInt("peer.gomaxprocs"))

	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed to initialize the crypto layer: %s", err))
	}

	// On failure Cobra prints the usage message and error string, so we only
	// need to exit with a non-0 status
	if mainCmd.Execute() != nil {
		os.Exit(1)
	}
	logger.Info("Exiting.....")
}
示例#30
0
func main() {
	// init config
	viper.SetConfigName("config") // name of config file (without extension)
	viper.AddConfigPath(".")

	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {
		log.Println(err)
		// Handle errors reading the config file
		viper.AutomaticEnv()
		//panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	// err = viper.Marshal(&C)
	// if err != nil {
	// 	log.Fatalf("unable to decode into struct, %v", err)
	// }
	//os.Getenv("PORT")

	// log.Println("Mimozaflowers port: ", viper.GetString("port"))

	C = config{CLIENTID: viper.GetString("clientid"),
		CLIENTSECRET: viper.GetString("clientsecret"),
		BASEURL:      viper.GetString("baseurl"),
		USERNAME:     viper.GetString("username"),
		PORT:         viper.GetString("port")}

	// set cache for data from instagram
	InstaCache = cache.New(5*time.Hour, 30*time.Minute)

	// Gin instance
	router := echo.New() //gin.Default()

	html := template.Must(template.New("").Funcs(template.FuncMap{"buildInstaFeed": buildInstaFeed}).ParseGlob("templates/*.html"))
	t := &Template{templates: html}
	router.SetRenderer(t)
	//router.SetHTMLTemplate(html)

	// Middleware
	router.Use(mw.Logger())
	router.Use(mw.Recover())

	// Routes
	router.Static("/js/", "public/js")
	router.Static("/css/", "public/css")
	router.Get("/", recentMedia)

	// Start server
	//err = router.Run(":" + C.PORT)

	//graceful.Run(":"+C.PORT, 5*time.Second, router)
	//graceful.ListenAndServe(router.Server(":"+C.PORT), 5*time.Second)
	router.Run(":" + C.PORT)
	// if err != nil {
	// 	log.Println("Error: ", err)
	// }

}