當前位置: 首頁>>代碼示例>>Golang>>正文


Golang viper.AutomaticEnv函數代碼示例

本文整理匯總了Golang中github.com/spf13/viper.AutomaticEnv函數的典型用法代碼示例。如果您正苦於以下問題:Golang AutomaticEnv函數的具體用法?Golang AutomaticEnv怎麽用?Golang AutomaticEnv使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了AutomaticEnv函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: LoadConfig

// 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)
}
開發者ID:GrappigPanda,項目名稱:notorious,代碼行數:27,代碼來源:config.go

示例2: Start

// 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
}
開發者ID:RicHernandez2,項目名稱:fabric,代碼行數:35,代碼來源:chaincode.go

示例3: newConfig

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
}
開發者ID:RobinUS2,項目名稱:indispenso,代碼行數:60,代碼來源:conf.go

示例4: Init

// 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
}
開發者ID:romana,項目名稱:core,代碼行數:27,代碼來源:service.go

示例5: initConfig

// 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()
		}
	}
}
開發者ID:Codaisseur,項目名稱:deis-backing-services,代碼行數:31,代碼來源:root.go

示例6: Setup

// 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
}
開發者ID:Ritsyy,項目名稱:almighty-core,代碼行數:35,代碼來源:configuration.go

示例7: init

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"))
}
開發者ID:cgt212,項目名稱:cassfs,代碼行數:26,代碼來源:root.go

示例8: main

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")
		}
	}
}
開發者ID:emccode,項目名稱:mars-challenge,代碼行數:25,代碼來源:publisher.go

示例9: Start

// 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
}
開發者ID:masterDev1985,項目名稱:obc-peer,代碼行數:34,代碼來源:chaincode.go

示例10: initConfig

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

	viper.SetConfigName(".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)
	}
}
開發者ID:tahitianstud,項目名稱:ata,代碼行數:26,代碼來源:root.go

示例11: initConfig

// initConfig reads in config file and ENV variables if set.
func initConfig() {

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

	viper.SetConfigName(".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)
	}
}
開發者ID:jzorn,項目名稱:grnl,代碼行數:28,代碼來源:grnl.go

示例12: initConfig

// 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)
	}
}
開發者ID:lursu,項目名稱:skelly,代碼行數:35,代碼來源:root.go

示例13: LoadGlobalConfig

// 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
}
開發者ID:tubo028,項目名稱:hugo,代碼行數:30,代碼來源:config.go

示例14: init

func init() {
	viper.SetConfigType("yaml")
	viper.AutomaticEnv()

	envReplacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(envReplacer)
}
開發者ID:ricobl,項目名稱:beat,代碼行數:7,代碼來源:config.go

示例15: processVars

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)
}
開發者ID:ptrimble,項目名稱:dreamhost-personal-backup,代碼行數:29,代碼來源:main.go


注:本文中的github.com/spf13/viper.AutomaticEnv函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。