本文整理汇总了Golang中github.com/spf13/viper.SetDefault函数的典型用法代码示例。如果您正苦于以下问题:Golang SetDefault函数的具体用法?Golang SetDefault怎么用?Golang SetDefault使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SetDefault函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestMain
func TestMain(m *testing.M) {
// start influx
// configure influx to connect to (DO NOT TEST ON PRODUCTION)
// viper.SetDefault("influx-address", "http://localhost:8086")
viper.SetDefault("influx-address", "http://172.28.128.4:8086")
viper.SetDefault("aggregate-interval", 1)
// initialize influx
queries := []string{
// clean influx to test with (DO NOT RUN ON PRODUCTION)
"DROP DATABASE statistics",
"CREATE DATABASE statistics",
`CREATE RETENTION POLICY one_day ON statistics DURATION 2d REPLICATION 1 DEFAULT`,
`CREATE RETENTION POLICY one_week ON statistics DURATION 1w REPLICATION 1`,
}
for _, query := range queries {
_, err := influx.Query(query)
if err != nil {
fmt.Printf("Failed to QUERY/INITIALIZE - '%v' skipping tests\n", err)
os.Exit(0)
}
}
rtn := m.Run()
_, err := influx.Query("DROP DATABASE statistics")
if err != nil {
fmt.Println("Failed to CLEANUP - ", err)
os.Exit(1)
}
os.Exit(rtn)
}
示例2: init
func init() {
// default values
// If no config is found, use the default(s)
viper.SetDefault("port", 80)
viper.SetDefault("crate_rest_api", "")
viper.SetDefault("crate", false)
// environment variable
viper.SetEnvPrefix("fci") // will be uppercased automatically
viper.BindEnv("port")
viper.BindEnv("crate")
viper.BindEnv("crate_rest_api")
// config file
viper.AddConfigPath("./")
viper.SetConfigName("config")
err := viper.ReadInConfig()
// check if configfile is available
if err != nil {
fmt.Println("No configuration file loaded")
// os.Exit(1)
}
}
示例3: 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
}
示例4: 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)
}
}
}
示例5: init
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags, which, if defined here,
// will be global for your application.
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.nessusControl.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
RootCmd.PersistentFlags().StringP("username", "u", "admin", "The username to log into Nessus.")
RootCmd.PersistentFlags().StringP("password", "a", "Th1sSh0u1dB3AStr0ngP422w0rd", "The password to use to log into Nessus.")
RootCmd.PersistentFlags().StringP("hostname", "o", "127.0.0.1", "The host where Nessus is located.")
RootCmd.PersistentFlags().StringP("port", "p", "8834", "The port number used to connect to Nessus.")
RootCmd.PersistentFlags().BoolP("debug", "d", false, "Use this flag to enable debug mode")
viper.BindPFlag("auth.username", RootCmd.PersistentFlags().Lookup("username"))
viper.SetDefault("auth.username", "admin")
viper.BindPFlag("auth.password", RootCmd.PersistentFlags().Lookup("password"))
viper.SetDefault("auth.password", "Th1sSh0u1dB3AStr0ngP422w0rd")
viper.BindPFlag("nessusLocation.hostname", RootCmd.PersistentFlags().Lookup("hostname"))
viper.SetDefault("nessusLocation.hostname", "127.0.0.1")
viper.BindPFlag("nessusLocation.port", RootCmd.PersistentFlags().Lookup("port"))
viper.SetDefault("nessusLocation.port", "8834")
viper.BindPFlag("debug", RootCmd.PersistentFlags().Lookup("debug"))
viper.SetDefault("debug", "8834")
}
示例6: 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)
}
示例7: 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")
}
}
}
示例8: 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)
}
示例9: init
func init() {
RootCmd.AddCommand(serveCmd)
// @NOTE: Do not set the default values here, that doesn't work correctly!
serveCmd.Flags().BoolP("daemon", "d", false, "Run as a daemon and detach from terminal")
serveCmd.Flags().StringP("address", "a", "", "Set address:port to listen on")
serveCmd.Flags().StringP("domain", "e", "", "Set domain to use with cookies")
serveCmd.Flags().StringP("databasepath", "f", "", "Set path to database where the user infos are stored")
serveCmd.Flags().IntP("cookiemaxage", "m", 4, "Set magical cookie's lifetime before it expires (in hours)")
serveCmd.Flags().StringP("cookiesecret", "c", "", "Secret string to use in signing cookies")
viper.BindPFlag("address", serveCmd.Flags().Lookup("address"))
viper.BindPFlag("domain", serveCmd.Flags().Lookup("domain"))
viper.BindPFlag("databasepath", serveCmd.Flags().Lookup("databasepath"))
viper.BindPFlag("cookiemaxage", serveCmd.Flags().Lookup("cookiemaxage"))
viper.BindPFlag("cookiesecret", serveCmd.Flags().Lookup("cookiesecret"))
viper.SetDefault("address", "127.0.0.1:9434")
viper.SetDefault("domain", ".secure.mydomain.eu")
viper.SetDefault("databasepath", "./database.json")
viper.SetDefault("cookiemaxage", 4)
viper.SetDefault("cookiesecret", "CHOOSE-A-SECRET-YOURSELF")
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// serveCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// serveCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
示例10: 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)
}
示例11: main
func main() {
// config defaults
viper.SetDefault("SigningKey", "change me in config/app.toml")
viper.SetDefault("Port", "8888")
viper.SetDefault("Database", "postgresql")
viper.SetConfigType("toml")
viper.SetConfigName("app")
viper.AddConfigPath("./config/")
// TODO better error message
err := viper.ReadInConfig()
if err != nil {
fmt.Print(fmt.Errorf("Fatal error config file: %s \n", err))
fmt.Println("Config path is ./config/, and name should be app.toml")
fmt.Println("Using defaults")
}
// TODO: check toml for nested propeties
// TODO: Handle config in a separate module? file?
dbConfig := viper.GetStringMap("Database")
dbName := dbConfig["Name"]
dbUser := dbConfig["User"]
// fmt.Sprintf("user=%s dbname=%s sslmode=disable", dbUser, dbName)
dbOptions := db.Options{
Driver: "postgres",
Params: fmt.Sprintf("user=%s dbname=%s sslmode=disable", dbUser, dbName),
}
dbConnection := db.Connect(dbOptions)
app := NewApp([]byte(viper.GetString("SigningKey")), dbConnection)
port := viper.GetString("Port")
log.Printf("Serving on port: %s\n", port)
app.E.Run(":" + port)
}
示例12: main
func main() {
viper.SetDefault("addr", "127.0.0.1")
viper.SetDefault("httpListen", ":3000")
viper.SetConfigName("config")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
fmt.Printf("Fatal error config file: %s \n,now using default value", err)
}
addr := viper.GetString("addr")
httpListen := viper.GetString("httpListen")
m := staticbin.Classic(handler.Asset)
zc := zk.New(addr)
m.Map(zc)
m.Use(render.Renderer(render.Options{
Delims: render.Delims{"{[{", "}]}"}, // Sets delimiters to the specified strings.
}))
m.Get("/", handler.Tree)
m.Get("/lookup", handler.LookUp)
m.Get("/nodes", handler.Childrens)
m.Get("/node", handler.NodeData)
m.Get("/state", handler.State)
m.Post("/create", handler.Create)
m.Post("/edit", handler.Edit)
m.Post("/rmr", handler.Rmr)
m.Post("/delete", handler.Delete)
m.Get("/export", handler.Export)
m.Post("/import", handler.Import)
m.Get("/find", handler.FindByPath)
m.RunOnAddr(httpListen)
}
示例13: InitializeCertAuthConfig
// InitializeCertAuthConfig sets up the command line options for creating a CA
func InitializeCertAuthConfig(logger log.Logger) error {
viper.SetDefault("Bits", "4096")
viper.SetDefault("Years", "10")
viper.SetDefault("Organization", "kappa-ca")
viper.SetDefault("Country", "USA")
if initCmd.PersistentFlags().Lookup("bits").Changed {
logger.Info("", "Bits", KeyBits)
viper.Set("Bits", KeyBits)
}
if initCmd.PersistentFlags().Lookup("years").Changed {
logger.Info("", "Years", Years)
viper.Set("Years", Years)
}
if initCmd.PersistentFlags().Lookup("organization").Changed {
logger.Info("", "Organization", Organization)
viper.Set("Organization", Organization)
}
if initCmd.PersistentFlags().Lookup("country").Changed {
logger.Info("", "Country", Country)
viper.Set("Country", Country)
}
if initCmd.PersistentFlags().Lookup("hosts").Changed {
logger.Info("", "Hosts", Hosts)
viper.Set("Hosts", Hosts)
}
return nil
}
示例14: InitializeConfig
// InitializeConfig initializes a config file with sensible default configuration flags.
func InitializeConfig() {
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() // FIXME
if err != nil {
jww.INFO.Println("Unable to locate Config file. I will fall back to my defaults...")
}
// default settings
viper.SetDefault("Verbose", false)
viper.SetDefault("DryRun", false)
viper.SetDefault("DoLog", true)
// bind config to command flags
if grasshopperCmdV.PersistentFlags().Lookup("verbose").Changed {
viper.Set("Verbose", Verbose)
}
if grasshopperCmdV.PersistentFlags().Lookup("log").Changed {
viper.Set("DoLog", DoLog)
}
}
示例15: initConfig
func initConfig() {
// defaults
viper.SetDefault("adminroot", "/admin/") // front end location of admin
viper.SetDefault("admindir", "./admin") // location of admin assets (relative to site directory)
viper.SetDefault("contentdir", "content")
// config name and location
viper.SetConfigName("config")
viper.AddConfigPath("/etc/topiary")
viper.AddConfigPath(".")
// read config
err := viper.ReadInConfig()
if err != nil {
fmt.Println("No topiary config found. Using defaults.")
}
// watch config ; TODO : config to turn this on/off
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
})
}