本文整理汇总了Golang中github.com/spf13/viper.SetDefault函数的典型用法代码示例。如果您正苦于以下问题:Golang SetDefault函数的具体用法?Golang SetDefault怎么用?Golang SetDefault使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SetDefault函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
}
开发者ID:nanopack,项目名称:pulse,代码行数:34,代码来源:influx_test.go
示例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)
}
}
开发者ID:firecyberice,项目名称:demowebserver,代码行数:25,代码来源:main.go
示例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
}
开发者ID:kadel,项目名称:grasshopper,代码行数:32,代码来源:grasshopper.go
示例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)
}
}
}
开发者ID:yukkurisinai,项目名称:omoikane,代码行数:35,代码来源:server.go
示例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")
}
开发者ID:kkirsche,项目名称:nessusControl,代码行数:27,代码来源:root.go
示例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)
}
开发者ID:chop-dbhi,项目名称:scds,代码行数:35,代码来源:config.go
示例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")
}
}
}
开发者ID:emccode,项目名称:mars-challenge,代码行数:25,代码来源:publisher.go
示例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)
}
开发者ID:spencergibb,项目名称:go-nuvem,代码行数:25,代码来源:discoveryserverlist_test.go
示例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")
}
开发者ID:lstep,项目名称:2fanginx,代码行数:34,代码来源:serve.go
示例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)
}
开发者ID:mcqueenorama,项目名称:telnet-chat,代码行数:34,代码来源:chat.go
示例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)
}
开发者ID:q1t,项目名称:movielist,代码行数:35,代码来源:main.go
示例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)
}
开发者ID:zhaojkun,项目名称:zkeditor,代码行数:31,代码来源:main.go
示例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
}
开发者ID:blacklabeldata,项目名称:kappa,代码行数:31,代码来源:init-ca.go
示例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)
}
}
开发者ID:vpavlin,项目名称:grasshopper,代码行数:26,代码来源:grasshopper.go
示例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)
})
}
开发者ID:topiary-io,项目名称:topiary,代码行数:25,代码来源:config.go
示例16: main
func main() {
viper.SetEnvPrefix("SENSOR")
viper.SetDefault("listen_address", ss.DefaultRadWSAddr)
viper.SetDefault("flare_address", "localhost"+ss.DefaultFlareWSAddr)
viper.AutomaticEnv()
rand.Seed(time.Now().UTC().UnixNano())
reading := &types.RadiationReading{
Radiation: ss.InitRadiation,
}
flareExit := make(chan bool)
flareAddr := viper.GetString("flare_address")
go types.FlareUpdateRoutine(reading, &flareAddr, flareExit)
go radiationRoutine(reading)
addr := viper.GetString("listen_address")
blaster := wsblaster.GetBlaster(&addr, false)
go blaster.Run()
ticker := time.NewTicker(1 * time.Second)
for {
select {
case <-ticker.C:
reading.RLock()
m, _ := json.Marshal(reading)
reading.RUnlock()
blaster.Write(m)
case <-flareExit:
log.Fatal("Unable to connect to Solar Flare source")
}
}
}
开发者ID:emccode,项目名称:mars-challenge,代码行数:33,代码来源:radiation.go
示例17: init
func init() {
cobra.OnInitialize(initConfig)
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory, e.g. github.com/spf13/")
RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)")
RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))
viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase"))
viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper"))
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
viper.SetDefault("license", "apache")
viper.SetDefault("licenseText", `
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
`)
}
开发者ID:CyCoreSystems,项目名称:coreos-kubernetes,代码行数:25,代码来源:root.go
示例18: setupViper
func setupViper() {
viper.SetEnvPrefix(constants.MiniShiftEnvPrefix)
viper.AutomaticEnv()
viper.SetDefault(config.WantUpdateNotification, true)
viper.SetDefault(config.ReminderWaitPeriodInHours, 24)
setFlagsUsingViper()
}
开发者ID:rawlingsj,项目名称:gofabric8,代码行数:8,代码来源:root.go
示例19: 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
示例20: readConfig
func readConfig() {
viper.SetEnvPrefix("chat")
viper.SetDefault("database_url", "postgres:///chat_development?sslmode=disable")
viper.SetDefault("bind_address", "localhost:8080")
viper.AutomaticEnv()
viper.BindEnv("database_url")
viper.BindEnv("bind_address")
}
开发者ID:arrowcircle,项目名称:messenger,代码行数:8,代码来源:main.go
注:本文中的github.com/spf13/viper.SetDefault函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论