本文整理汇总了Golang中github.com/spf13/viper.SetConfigType函数的典型用法代码示例。如果您正苦于以下问题:Golang SetConfigType函数的具体用法?Golang SetConfigType怎么用?Golang SetConfigType使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SetConfigType函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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: 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)
*/
}
开发者ID:mehulsbhatt,项目名称:sandbox-1,代码行数:27,代码来源:main.go
示例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
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:35,代码来源:configuration.go
示例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))
}
}
开发者ID:muxx,项目名称:slack-redmine-bot,代码行数:28,代码来源:main.go
示例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)
}
}
开发者ID:HackG,项目名称:bloomnpi,代码行数:33,代码来源:bloomnpi.go
示例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)")
}
}
}()
}
开发者ID:McLeod095,项目名称:telebot,代码行数:33,代码来源:models.go
示例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
}
开发者ID:RobinUS2,项目名称:indispenso,代码行数:60,代码来源:conf.go
示例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
}
开发者ID:romana,项目名称:core,代码行数:27,代码来源:service.go
示例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)
}
}
开发者ID:lursu,项目名称:skelly,代码行数:35,代码来源:root.go
示例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()
}
开发者ID:jxstanford,项目名称:stormpath-sdk-go,代码行数:31,代码来源:config.go
示例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"))
}
开发者ID:cgt212,项目名称:cassfs,代码行数:26,代码来源:root.go
示例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()
}
开发者ID:masterDev1985,项目名称:obc-peer,代码行数:28,代码来源:server.go
示例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)
}
开发者ID:spencergibb,项目名称:go-nuvem,代码行数:25,代码来源:discoveryserverlist_test.go
示例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
}
开发者ID:kadel,项目名称:grasshopper,代码行数:32,代码来源:grasshopper.go
示例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)
}
开发者ID:mcqueenorama,项目名称:telnet-chat,代码行数:34,代码来源:chat.go
示例16: init
func init() {
jww.SetLogThreshold(jww.LevelTrace)
jww.SetStdoutThreshold(jww.LevelInfo)
log.Println("initing config ...")
viper.SetConfigName("zookeeper-helper")
viper.AddConfigPath("./")
viper.AddConfigPath("$HOME/.omega/")
viper.AddConfigPath("/etc/omega/")
viper.SetConfigType("yaml")
if err := viper.ReadInConfig(); err != nil {
log.Panicln("can't read config file:", err)
}
initDefault()
if err := viper.Unmarshal(&pairs); err != nil {
log.Panicln("can't covert to config pairs: ", err)
}
if !pairs.Debugging {
jww.SetLogThreshold(jww.LevelError)
jww.SetStdoutThreshold(jww.LevelError)
}
log.Printf("initialized config pairs: %+v\n", pairs)
}
开发者ID:Dataman-Cloud,项目名称:zookeeper-helper,代码行数:29,代码来源:config.go
示例17: main
func main() {
viper.SetDefault("port", 3000)
viper.SetDefault("udpBufSize", 1024)
viper.SetConfigType("json")
viper.SetConfigName("config")
viper.AddConfigPath("./config")
err := viper.ReadInConfig()
if err != nil {
log.Fatal("Config file ", err)
}
port := viper.GetString("port")
udpAddr, err := net.ResolveUDPAddr("udp4", ":"+port)
if err != nil {
log.Fatal("Resolve udp addr ", err)
}
conn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
log.Fatal(err)
}
log.Println("Server is starting on " + port)
size := viper.GetInt("udpBufSize")
client := handler.NewClient()
for {
buf := make([]byte, size)
rlen, addr, err := conn.ReadFromUDP(buf)
if err != nil {
conn.WriteToUDP([]byte("error"), addr)
} else {
go client.Handle(conn, addr, rlen, buf)
}
}
}
开发者ID:yukkurisinai,项目名称:omoikane,代码行数:35,代码来源:server.go
示例18: LoadSettingsFromFile
func LoadSettingsFromFile() {
viper.SetConfigType(ConfigType)
setConfigLocation()
// Set defaults
viper.SetDefault("Port", Port)
viper.SetDefault("EnableAutomerge", EnableAutomerge)
viper.SetDefault("Debug", Debug)
viper.SetDefault("DefaultEnvironment", DefaultEnvironment)
viper.SetDefault("DefaultTask", DefaultTask)
viper.SetDefault("BoltdbName", BoltdbName)
// Load configuration
err := viper.ReadInConfig()
if err != nil {
log.Warning("Configuration not found, loading defaults")
}
// set log level
if viper.GetBool("Debug") {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
log.Debugf("Loaded setting values: %v", viper.AllSettings())
log.Info("Settings loaded")
}
开发者ID:slok,项目名称:daton,代码行数:28,代码来源:load.go
示例19: InitConfig
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)
}
开发者ID:chop-dbhi,项目名称:scds,代码行数:35,代码来源:config.go
示例20: init
func init() {
viper.SetConfigType("yaml")
viper.AutomaticEnv()
envReplacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(envReplacer)
}
开发者ID:ricobl,项目名称:beat,代码行数:7,代码来源:config.go
注:本文中的github.com/spf13/viper.SetConfigType函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论