当前位置: 首页>>代码示例>>Golang>>正文


Golang viper.SetConfigFile函数代码示例

本文整理汇总了Golang中github.com/spf13/viper.SetConfigFile函数的典型用法代码示例。如果您正苦于以下问题:Golang SetConfigFile函数的具体用法?Golang SetConfigFile怎么用?Golang SetConfigFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了SetConfigFile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: 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

示例2: initConfig

// 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)
	}
}
开发者ID:mfojtik,项目名称:dev-tools,代码行数:34,代码来源:root.go

示例3: NewConfig

func NewConfig() (*Config, error) {
	flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)

	c := Config{}
	flags.StringVarP(&c.URL, "url", "u", "", "the url")
	viper.BindPFlag("url", flags.Lookup("url"))

	// This doesn't need to be in the Config struct, because we're just using it to override viper.
	file := flags.StringP("file", "f", "", "name of the config file")

	// Parse the command line args into the flag set, ignoring the command name.
	flags.Parse(os.Args[1:])

	if *file != "" {
		viper.SetConfigFile(*file)
	}

	if err := viper.ReadInConfig(); err != nil {
		return nil, err
	}

	if err := viper.Unmarshal(&c); err != nil {
		return nil, err
	}

	return &c, nil
}
开发者ID:kytrinyx,项目名称:venom-example,代码行数:27,代码来源:config.go

示例4: 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(".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)
	}
}
开发者ID:goern,项目名称:gogetgithubstats,代码行数:35,代码来源:root.go

示例5: 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

示例6: SetupTest

func (suite *GitConfigTestSuite) SetupTest() {
	assert := assert.New(suite.T())
	viper.SetConfigFile("../../.ayi.example.yml")
	err := viper.ReadInConfig()
	assert.Nil(err)
	assert.Equal(true, viper.Get("debug"))
}
开发者ID:dyweb,项目名称:Ayi,代码行数:7,代码来源:config_test.go

示例7: loadConfig

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()
}
开发者ID:jxstanford,项目名称:stormpath-sdk-go,代码行数:31,代码来源:config.go

示例8: 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

示例9: 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

示例10: InitConfig

func InitConfig(configFile string) {
	SetDefaults()

	if configFile != "" {
		if _, err := os.Stat(configFile); os.IsNotExist(err) {
			log.WithFields(log.Fields{"file": configFile}).Fatal("Config file does not exist")
		}

		// Load the config file if supplied
		viper.SetConfigFile(configFile)
	} else {
		// Otherwise use the defaults
		viper.SetConfigName("agent")
		viper.AddConfigPath("/etc/reeve")
		viper.AddConfigPath("$HOME/.reeve")
	}

	err := viper.ReadInConfig()
	if err != nil {
		// Check if we got an unsupported config error
		// If so it means that no files were found, and we can just skip it using our defaults
		_, ok := err.(viper.UnsupportedConfigError)
		if !ok {
			log.WithError(err).Fatal("Could not read config")
		}

		log.Debug("No config file available, using all defaults")
	}
}
开发者ID:borgstrom,项目名称:reeve,代码行数:29,代码来源:config.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(".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

示例12: 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

示例13: main

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()
}
开发者ID:glycerine,项目名称:origins,代码行数:59,代码来源:main.go

示例14: initConfig

func initConfig() {
	viper.SetConfigFile("./config.json")
	viper.SetDefault("listen", ":8000")
	viper.SetDefault("staticFolder", "./static")
	viper.SetDefault("commandsFolder", "./commands")
	viper.SetDefault("log.filename", "go-lazy-remote.log")
	viper.ReadInConfig()
}
开发者ID:Opiskull,项目名称:go-lazy-remote,代码行数:8,代码来源:configuration.go

示例15: initConfig

func initConfig() {
	if CfgFile != "" {
		viper.SetConfigFile(CfgFile)
	}
	viper.SetConfigName("config")             // name of config file (without extension)
	viper.AddConfigPath(defaultDataDir + "/") // path to look for the config file in
	viper.ReadInConfig()
}
开发者ID:jpoehls,项目名称:feedmailer,代码行数:8,代码来源:main.go


注:本文中的github.com/spf13/viper.SetConfigFile函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。