本文整理汇总了Golang中github.com/spf13/viper.SetConfigType函数的典型用法代码示例。如果您正苦于以下问题:Golang SetConfigType函数的具体用法?Golang SetConfigType怎么用?Golang SetConfigType使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SetConfigType函数的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)
}
示例2: main
func main() {
viper.SetDefault("ConfigFile", "$HOME/.krb.jira.json")
viper.SetConfigName(".krb.jira")
viper.SetConfigType("json")
//viper.AddConfigPath("$HOME")
viper.AddConfigPath(".")
viper.ReadInConfig()
fmt.Printf("host:%s\n", viper.GetString("host"))
fmt.Printf("port:%d\n", viper.GetInt("port"))
fmt.Printf("user:%s\n", viper.GetString("user"))
fmt.Printf("pass:%s\n", viper.GetString("pass"))
apiInfo := &JiraApiInfo{}
viper.MarshalKey("apiInfo", &apiInfo)
fmt.Printf("apiInfo:%q\n", apiInfo)
// NB: marshaling this whole struct doesn't seem to work?
/*
config := &ConfigInfo{}
err := viper.Marshal(&config)
if err != nil {
panic(err)
}
fmt.Printf("config:%q\n", config)
*/
}
示例3: 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
}
示例4: configInit
func configInit() {
viper.SetEnvPrefix("srb")
var configPath string
flag.StringVar(&configPath, "config", "", "Path of configuration file without name (name must be config.yml)")
flag.Parse()
if len(configPath) > 0 {
viper.AddConfigPath(configPath)
}
configPath = os.Getenv("SRB_CONFIG")
if len(configPath) > 0 {
viper.AddConfigPath(configPath)
}
viper.AddConfigPath("/etc/slack-redmine-bot/")
viper.AddConfigPath(".")
viper.SetConfigName("config")
viper.SetConfigType("yaml")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Error in config file. %s \n", err))
}
}
示例5: main
func main() {
if len(os.Args) != 2 {
fmt.Println("Invalid command usage\n")
showUsage()
os.Exit(1)
}
arg := os.Args[1]
viper.SetConfigName("config")
viper.SetConfigType("toml")
viper.AddConfigPath("./")
err := viper.ReadInConfig()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
switch arg {
case "bootstrap":
npi.Bootstrap()
case "fetch":
npi.Fetch()
case "drop":
npi.Drop()
case "search-index":
npi.SearchIndex()
default:
fmt.Println("Invalid command:", arg)
showUsage()
os.Exit(1)
}
}
示例6: init
func init() {
viper.SetConfigName("telebot")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.AddConfigPath("$HOME/.telebot")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
dsn = fmt.Sprintf("%s:%[email protected](%s:%s)/%s?charset=utf8",
viper.GetString("mysql.telebot.user"),
viper.GetString("mysql.telebot.password"),
viper.GetString("mysql.telebot.host"),
viper.GetString("mysql.telebot.port"),
viper.GetString("mysql.telebot.dbname"))
db, err = sql.Open("mysql", dsn)
checkErr(err)
err = db.Ping()
checkErr(err)
go func() {
tick := time.Tick(rTime * time.Second)
for range tick {
if err := db.Ping(); err != nil {
log.Println("Connection to DB lost (try reconnect after", rTime, "seconds)")
}
}
}()
}
示例7: 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
}
示例8: 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
}
示例9: 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)
}
}
示例10: 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()
}
示例11: 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"))
}
示例12: main
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()
}
示例13: TestDiscoveryFactory
func TestDiscoveryFactory(t *testing.T) {
viper.SetConfigType("yaml")
yaml := []byte(`
nuvem.discovery.testdsl.static.servers:
- localhost:8080
- 127.0.0.1:9080
`)
err := viper.ReadConfig(bytes.NewBuffer(yaml))
viper.SetDefault("nuvem.discovery.testdsl.factory", discovery.StaticFactoryKey)
viper.SetDefault("nuvem.loadbalancer.serverlist.testdsl.factory", DisoveryFactoryKey)
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
// servers := viper.GetStringSlice("nuvem.loadbalancer.test.static.servers")
// fmt.Printf("%+v\n", servers)
// factory := viper.GetString("nuvem.loadbalancer.test.factory")
// fmt.Printf("%+v\n", factory)
serverList := Create("testdsl")
servers := assertServerList(t, serverList, 2)
assertServer(t, servers[0], "localhost", 8080)
assertServer(t, servers[1], "127.0.0.1", 9080)
}
示例14: InitializeConfig
// InitializeConfig reads in config file and ENV variables if set.
func InitializeConfig(subCmdVs ...*cobra.Command) error {
viper.SetConfigType("json")
viper.SetConfigName("grasshopper") // name of config file (without extension)
// viper.AddConfigPath("/etc/grasshopper.d/") // path to look for the config file
// viper.AddConfigPath("$HOME/.grasshopper.d") // call multiple times to add many search paths
viper.AddConfigPath(".") // optionally look for config in the working directory
// read config from storage
err := viper.ReadInConfig()
if err != nil {
jww.WARN.Printf("Unable to read Config file. %#v I will fall back to my defaults...", err)
err = nil // we just skip this error
}
// set some sane defaults
viper.SetDefault("Verbose", false)
viper.SetDefault("Quiet", false)
viper.SetDefault("Log", true)
viper.SetDefault("Experimental", true)
if grasshopperCmdV.PersistentFlags().Lookup("verbose").Changed {
viper.Set("Verbose", Verbose)
}
if viper.GetBool("verbose") {
jww.SetStdoutThreshold(jww.LevelTrace)
jww.SetLogThreshold(jww.LevelTrace)
}
return err
}
示例15: main
func main() {
var configDefault string = "chat"
viper.SetConfigName(configDefault)
viper.SetConfigType("toml")
viper.AddConfigPath("./")
viper.SetDefault(telnetIPWord, "127.0.0.1")
viper.SetDefault(telnetPortWord, "6000")
viper.SetDefault(apiIPWord, "127.0.0.1")
viper.SetDefault(apiPortWord, "6001")
err := viper.ReadInConfig()
if err != nil {
fmt.Printf("No configuration file found:%s:err:%v: - using defaults\n", configDefault, err)
}
logFile := viper.GetString("logFile")
log.MustSetupLogging(logFile)
log.Info("listening on:telnet:%s:%s:api:%s:%s:\n", viper.GetString(telnetIPWord), viper.GetString(telnetPortWord), viper.GetString(apiIPWord), viper.GetString(apiPortWord))
msgchan := make(chan m.ChatMsg)
addchan := make(chan client.Client)
rmchan := make(chan client.Client)
go handleMessages(msgchan, addchan, rmchan)
go telnet.TelnetServer(viper.GetString(telnetIPWord), viper.GetString(telnetPortWord), msgchan, addchan, rmchan)
api.ApiServer(viper.GetString(apiIPWord), viper.GetString(apiPortWord), msgchan, addchan, rmchan)
}