當前位置: 首頁>>代碼示例>>Golang>>正文


Golang viper.ReadInConfig函數代碼示例

本文整理匯總了Golang中github.com/spf13/viper.ReadInConfig函數的典型用法代碼示例。如果您正苦於以下問題:Golang ReadInConfig函數的具體用法?Golang ReadInConfig怎麽用?Golang ReadInConfig使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了ReadInConfig函數的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)
}
開發者ID:GrappigPanda,項目名稱:notorious,代碼行數:27,代碼來源:config.go

示例2: 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()
}
開發者ID:Pmaene,項目名稱:hkmpower,代碼行數:32,代碼來源:hkmpowerd.go

示例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"))
}
開發者ID:Chipsterjulien,項目名稱:zut,代碼行數:35,代碼來源:loadConfig.go

示例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 {}
}
開發者ID:stayradiated,項目名稱:autowatch,代碼行數:32,代碼來源:main.go

示例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()
}
開發者ID:sgoings,項目名稱:rigger,代碼行數:35,代碼來源:rigger.go

示例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)
	}
}
開發者ID:jakebailey,項目名稱:botzik,代碼行數:34,代碼來源:main.go

示例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)

}
開發者ID:mcqueenorama,項目名稱:telnet-chat,代碼行數:34,代碼來源:chat.go

示例8: run

func run(cmd *cobra.Command, args []string) {
	err := viper.ReadInConfig()
	if err != nil {
		log.Fatal("Error reading config_compliance.toml file: ", err)
	}

	var config config.Config
	err = viper.Unmarshal(&config)

	err = config.Validate()
	if err != nil {
		log.Fatal(err.Error())
		return
	}

	if config.LogFormat == "json" {
		log.SetFormatter(&log.JSONFormatter{})
	}

	app, err = compliance.NewApp(config, migrateFlag)

	if err != nil {
		log.Fatal(err.Error())
		return
	}

	app.Serve()
}
開發者ID:FihlaTV,項目名稱:bridge-server,代碼行數:28,代碼來源:main.go

示例9: readConfig

func readConfig() {

	user, _ := user.Current()
	configFolder := filepath.Join(user.HomeDir, ".blackpod")

	viper.SetConfigName("config")
	viper.AddConfigPath(configFolder)

	addProperty("feeds", "f", filepath.Join(configFolder, "feeds.dev"), "Feed file path")
	addProperty("directory", "d", "/tmp/test-podcasts", "Podcast folder path")
	addProperty("episodes", "e", 3, "Max episodes to download")
	addProperty("verbose", "v", false, "Enable verbose mode")
	addProperty("maxFeedRunner", "g", 5, "Max runners to fetch feeds")
	addProperty("maxImageRunner", "i", 3, "Max runners to fetch images")
	addProperty("maxEpisodeRunner", "j", 10, "Max runners to fetch episodes")
	addProperty("maxRetryDownload", "k", 3, "Max http retries")
	addProperty("maxCommentSize", "l", 500, "Max comment length")
	addProperty("retagExisting", "r", false, "Retag existing episodes")
	addProperty("dateFormat", "m", "020106", "Date format to be used in tags based on this reference date : Mon Jan _2 15:04:05 2006")
	addProperty("keptEpisodes", "n", 3, "Number of episodes to keep (0 or -1 means no old episode remval)")

	err := viper.ReadInConfig()
	if err != nil {
		logger.Error.Println("Fatal error config file: %s \n", err)
	}

}
開發者ID:jcnoir,項目名稱:goblackpodder,代碼行數:27,代碼來源:blackpodder.go

示例10: setup

func setup() {
	// Conf
	viper.SetConfigName("asset") // name of config file (without extension)
	viper.AddConfigPath(".")     // path to look for the config file in
	err := viper.ReadInConfig()  // Find and read the config file
	if err != nil {              // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error config file [%s] \n", err))
	}

	// Logging
	var formatter = logging.MustStringFormatter(
		`%{color}[%{module}] %{shortfunc} [%{shortfile}] -> %{level:.4s} %{id:03x}%{color:reset} %{message}`,
	)
	logging.SetFormatter(formatter)

	logging.SetLevel(logging.DEBUG, "peer")
	logging.SetLevel(logging.DEBUG, "chaincode")
	logging.SetLevel(logging.DEBUG, "cryptochain")

	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed initializing the crypto layer [%s]", err))
	}

	removeFolders()
}
開發者ID:yoshiharay,項目名稱:fabric,代碼行數:26,代碼來源:asset_management_with_roles_test.go

示例11: main

func main() {
	viper.ReadInConfig()

	/*
		var verbose bool = false
		var showConfig bool = false
		var host string = viper.GetString("host")
		var user string = viper.GetString("user")
	*/

	//flag.BoolVar(&showConfig, "show-config", showConfig, "Show configuration")
	//flag.BoolVar(&verbose, "verbose", verbose, "Be verbose.")
	//flag.StringVar(&host, "host", viper.GetString("host"), "Set the hostname.")
	//flag.StringVar(&user, "user", viper.GetString("user"), "Set the Jira user.")

	//flag.Parse()

	/*
		viper.Set("verbose", verbose)
		viper.Set("host", host)
		viper.Set("user", user)
	*/

	//	if showConfig {
	//		ShowConfig()
	//		os.Exit(0)
	//	}

	JiraCmd.Execute()
}
開發者ID:mehulsbhatt,項目名稱:sandbox-1,代碼行數:30,代碼來源:jira.go

示例12: initViper

func initViper() error {
	var err error

	viper.SetConfigName("sqlboiler")

	configHome := os.Getenv("XDG_CONFIG_HOME")
	homePath := os.Getenv("HOME")
	wd, err := os.Getwd()
	if err != nil {
		wd = "../"
	} else {
		wd = wd + "/.."
	}

	configPaths := []string{wd}
	if len(configHome) > 0 {
		configPaths = append(configPaths, filepath.Join(configHome, "sqlboiler"))
	} else {
		configPaths = append(configPaths, filepath.Join(homePath, ".config/sqlboiler"))
	}

	for _, p := range configPaths {
		viper.AddConfigPath(p)
	}

	// Ignore errors here, fall back to defaults and validation to provide errs
	_ = viper.ReadInConfig()
	viper.AutomaticEnv()

	return nil
}
開發者ID:zqzca,項目名稱:back,代碼行數:31,代碼來源:boil_main_test.go

示例13: 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

示例14: 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

示例15: 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


注:本文中的github.com/spf13/viper.ReadInConfig函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。