本文整理汇总了Golang中github.com/spf13/viper.SetConfigName函数的典型用法代码示例。如果您正苦于以下问题:Golang SetConfigName函数的具体用法?Golang SetConfigName怎么用?Golang SetConfigName使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SetConfigName函数的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: TestMain
func TestMain(m *testing.M) {
// setup mock rage4 api server()
go serverWebPages()
// get settings for rage4
viper.SetConfigName("testing") // can be testing.json, testing.yaml
viper.AddConfigPath("./example")
viper.ReadInConfig()
accountKey := viper.GetString("AccountKey")
email := viper.GetString("Email")
url := viper.GetString("URL")
fmt.Printf("testing rage4 api at %s using account %s\n", url, accountKey)
// create client to test API calls
client = Client{
AccountKey: accountKey,
Email: email,
URL: url,
Http: http.DefaultClient,
}
if (client == Client{}) {
os.Exit(-1)
}
retCode := m.Run()
fmt.Printf("result = %d", retCode)
// teardown()
os.Exit(retCode)
}
示例3: loadConfig
func loadConfig(filenamePath *string, filename *string) {
log := logging.MustGetLogger("log")
viper.SetConfigName(*filename)
viper.AddConfigPath(*filenamePath)
if err := viper.ReadInConfig(); err != nil {
log.Critical("Unable to load config file:", err)
os.Exit(1)
}
switch viper.GetString("logtype") {
case "critical":
logging.SetLevel(0, "")
case "error":
logging.SetLevel(1, "")
case "warning":
logging.SetLevel(2, "")
case "notice":
logging.SetLevel(3, "")
case "info":
logging.SetLevel(4, "")
case "debug":
logging.SetLevel(5, "")
log.Debug("\"debug\" is selected")
default:
logging.SetLevel(2, "")
//log.Debug("\"default\" is selected (warning)")
}
log.Debug("loadConfig func:")
log.Debug(" path: %s", *filenamePath)
log.Debug(" filename: %s", *filename)
log.Debug(" logtype in file config is \"%s\"", viper.GetString("logtype"))
}
示例4: main
func main() {
viper.SetConfigName("config")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
urls := viper.GetStringMapString("urls")
username := viper.GetString("auth.username")
password := viper.GetString("auth.password")
for title, url := range urls {
c := Checker{
Title: title,
URL: url,
Username: username,
Password: password,
}
go func() {
for {
if err := c.Check(); err != nil {
log.Println(err)
}
time.Sleep(time.Second * 5)
}
}()
}
select {}
}
示例5: main
func main() {
filter := &logutils.LevelFilter{
Levels: []logutils.LogLevel{"DEBUG", "INFO", "WARN", "ERROR"},
MinLevel: logutils.LogLevel("INFO"),
Writer: os.Stderr,
}
log.SetOutput(filter)
viper.SetConfigName("Rigfile")
viper.AddConfigPath("$HOME/.rigger/")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
if _, ok := err.(viper.UnsupportedConfigError); ok {
log.Printf("[ERROR] No Rigfile exists.")
os.Exit(1)
} else {
log.Printf("[ERROR] %s", err)
}
}
var cmdUp = &cobra.Command{
Use: "up",
Short: "Create my infrastructure",
Long: `Do lots of work`,
Run: func(cmd *cobra.Command, args []string) {
log.Printf("[INFO] Rigger lifting!")
},
}
var rootCmd = &cobra.Command{Use: "rigger"}
rootCmd.AddCommand(cmdUp)
rootCmd.Execute()
}
示例6: main
func main() {
pflag.Parse()
viper.SetConfigName("config")
viper.AddConfigPath(".")
if debug {
logrus.SetLevel(logrus.DebugLevel)
}
if err := viper.ReadInConfig(); err != nil {
logrus.Fatal(err)
}
nick := viper.GetString("twitch.nick")
pass := viper.GetString("twitch.pass")
channels := viper.GetStringSlice("twitch.join")
dbFilename := viper.GetString("database.filename")
superusers := viper.GetStringSlice("permissions.superusers")
bot := bot.NewBot(nick, pass, channels, dbFilename, superusers)
if err := bot.Start(); err != nil {
logrus.Fatal(err)
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
fmt.Print("\r\r\b")
if err := bot.Stop(); err != nil {
logrus.Fatal(err)
}
}
示例7: 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)
}
示例8: 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.AddConfigPath("./")
err := viper.ReadInConfig()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
switch arg {
case "server":
cmd.Server()
case "bootstrap":
cmd.Bootstrap()
case "drop":
cmd.Drop()
default:
fmt.Println("Invalid command:", arg)
showUsage()
os.Exit(1)
}
}
示例9: 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)
}
示例10: 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)
}
示例11: 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)
}
}
示例12: main
func main() {
switches = map[uint8]*HKSwitch{}
client = &http.Client{}
pinArg := flag.String("pin", "", "PIN used to pair the MPower switches with HomeKit")
configArg := flag.String("config", ".", "Directory where config.json is stored")
verboseArg := flag.Bool("v", false, "Whether or not log output is displayed")
flag.Parse()
pin = *pinArg
viper.SetConfigName("config")
viper.AddConfigPath(*configArg)
viper.ReadInConfig()
if !*verboseArg {
log.Info = false
log.Verbose = false
}
hc.OnTermination(func() {
for _, switcher := range switches {
switcher.transport.Stop()
}
time.Sleep(100 * time.Millisecond)
os.Exit(1)
})
Connect()
}
示例13: 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)
}
}
示例14: 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)
})
}
示例15: 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()
}