Example #1
2
// 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)
}
Example #2
0
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()
}
Example #3
0
func InitConfig(configFile string) {
	SetDefaults()

	if configFile != "" {
		if _, err := os.Stat(configFile); os.IsNotExist(err) {
			log.WithFields(log.Fields{"file": configFile}).Fatal("Config file does not exist")
		}

		// Load the config file if supplied
		viper.SetConfigFile(configFile)
	} else {
		// Otherwise use the defaults
		viper.SetConfigName("agent")
		viper.AddConfigPath("/etc/reeve")
		viper.AddConfigPath("$HOME/.reeve")
	}

	err := viper.ReadInConfig()
	if err != nil {
		// Check if we got an unsupported config error
		// If so it means that no files were found, and we can just skip it using our defaults
		_, ok := err.(viper.UnsupportedConfigError)
		if !ok {
			log.WithError(err).Fatal("Could not read config")
		}

		log.Debug("No config file available, using all defaults")
	}
}
Example #4
0
File: grnl.go Project: jzorn/grnl
// initConfig reads in config file and ENV variables if set.
func initConfig() {

	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".grnl") // name of config file (without extension)
	viper.AddConfigPath("$HOME") // adding home directory as first search path
	viper.AutomaticEnv()         // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err != nil {
		fmt.Printf("Error using config file %q\n%q", viper.ConfigFileUsed(), err)
	}

	if db != "" {
		viper.Set("db", db)
	}

	if editor != "" {
		viper.Set("editor", editor)
	}

	if dateFormat != "" {
		viper.Set("dateFormat", dateFormat)
	}
}
Example #5
0
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()
}
Example #6
0
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)
	}
}
Example #7
0
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)

}
Example #8
0
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()
}
Example #9
0
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)
	}

}
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()
}
Example #11
0
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()
}
Example #12
0
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
}
Example #13
0
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)
}
Example #14
0
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)
}
Example #15
0
// 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)
	}
}
Example #16
0
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)
	}
}
Example #17
0
func TestChangeDefaultLanguage(t *testing.T) {
	testCommonResetState()
	viper.Set("defaultContentLanguageInSubdir", false)

	sites := createMultiTestSites(t, testSiteConfig{DefaultContentLanguage: "fr"}, multiSiteTOMLConfigTemplate)
	cfg := BuildCfg{}

	err := sites.Build(cfg)

	if err != nil {
		t.Fatalf("Failed to build sites: %s", err)
	}

	assertFileContent(t, "public/sect/doc1/index.html", true, "Single", "Bonjour")
	assertFileContent(t, "public/en/sect/doc2/index.html", true, "Single", "Hello")

	newConfig := createConfig(t, testSiteConfig{DefaultContentLanguage: "en"}, multiSiteTOMLConfigTemplate)

	// replace the config
	writeSource(t, "multilangconfig.toml", newConfig)

	// Watching does not work with in-memory fs, so we trigger a reload manually
	require.NoError(t, viper.ReadInConfig())
	err = sites.Build(BuildCfg{CreateSitesFromConfig: true})

	if err != nil {
		t.Fatalf("Failed to rebuild sites: %s", err)
	}

	// Default language is now en, so that should now be the "root" language
	assertFileContent(t, "public/fr/sect/doc1/index.html", true, "Single", "Bonjour")
	assertFileContent(t, "public/sect/doc2/index.html", true, "Single", "Hello")
}
Example #18
0
File: load.go Project: slok/daton
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")
}
Example #19
0
func setup() {
	// Conf
	viper.SetConfigName("rbac") // 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, "cryptoain")

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

	hl := filepath.Join(os.TempDir(), "hyperledger")

	viper.Set("peer.fileSystemPath", filepath.Join(hl, "production"))
	viper.Set("server.rootpath", filepath.Join(hl, "ca"))

	removeFolders()
}
Example #20
0
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)
		}
	}
}
Example #21
0
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".ata")  // name of config file (without extension)
	viper.AddConfigPath("$HOME") // adding home directory as first search path
	viper.AutomaticEnv()         // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}

	// deal with verbose and debug mode
	if DebugMode {
		logger.SetLevel(logging.DebugLevel)
	}
	logger.ActivateVerboseOutput(VerboseMode)

	// check that work directory exists
	if !io.DirectoryExists(WorkDirectory) {
		log.Fatalf("Work directory '%s' does not exist or is not readable", WorkDirectory)
	}
}
Example #22
0
// Enable viper configuration management of flags.
func ViperizeFlags() {
	// TODO @jayunit100: Maybe a more elegant viper-flag integration for the future?
	// For now, we layer it on top, because 'flag' deps of 'go test' make pflag wrappers
	// fragile, seeming to force 'flag' to have deep awareness of pflag params.
	RegisterCommonFlags()
	RegisterClusterFlags()

	flag.Parse()

	// Add viper in a minimal way.
	// Flag interop isnt possible, since 'go test' coupling to flag.Parse.
	// This must be done after common flags are registered, since Viper is a flag option.
	viper.SetConfigName(TestContext.Viper)
	viper.AddConfigPath(".")
	viper.ReadInConfig()

	viper.Unmarshal(&TestContext)

	/** This can be used to overwrite a flag value.
	*
	*	viperFlagSetter := func(f *flag.Flag) {
	*		if viper.IsSet(f.Name) {
	*			glog.V(4).Infof("[viper config] Overwriting, found a settting for %v %v", f.Name, f.Value)
	*			viper.Unmarshal(&TestContext)
	*			// f.Value.Set(viper.GetString(f.Name))
	*		}
	*	}
	*	// Each flag that we've declared can be set via viper.
	*	flag.VisitAll(viperFlagSetter)
	*
	 */
}
Example #23
0
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)
}
Example #24
0
func handleSignals(app *libcentrifugo.Application) {
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, syscall.SIGHUP, syscall.SIGINT, os.Interrupt)
	for {
		sig := <-sigc
		logger.INFO.Println("signal received:", sig)
		switch sig {
		case syscall.SIGHUP:
			// reload application configuration on SIGHUP
			// note that you should run checkconfig before reloading configuration
			// as Viper exits when encounters parsing errors
			logger.INFO.Println("reloading configuration")
			err := viper.ReadInConfig()
			if err != nil {
				logger.CRITICAL.Println("unable to locate config file")
				return
			}
			setupLogging()
			c := newConfig()
			s := structureFromConfig(nil)
			app.SetConfig(c)
			app.SetStructure(s)
		case syscall.SIGINT, os.Interrupt:
			logger.INFO.Println("shutting down")
			go time.AfterFunc(5*time.Second, func() {
				os.Exit(1)
			})
			app.Shutdown()
			os.Exit(130)
		}
	}
}
Example #25
0
// LoadGlobalConfig loads Hugo configuration into the global Viper.
func LoadGlobalConfig(relativeSourcePath, configFilename string) error {

	if relativeSourcePath == "" {
		relativeSourcePath = "."
	}

	viper.AutomaticEnv()
	viper.SetEnvPrefix("hugo")
	viper.SetConfigFile(configFilename)
	// See https://github.com/spf13/viper/issues/73#issuecomment-126970794
	if relativeSourcePath == "" {
		viper.AddConfigPath(".")
	} else {
		viper.AddConfigPath(relativeSourcePath)
	}
	err := viper.ReadInConfig()
	if err != nil {
		if _, ok := err.(viper.ConfigParseError); ok {
			return err
		}
		return fmt.Errorf("Unable to locate Config file. Perhaps you need to create a new site.\n       Run `hugo help new` for details. (%s)\n", err)
	}

	viper.RegisterAlias("indexes", "taxonomies")

	loadDefaultSettings()

	return nil
}
Example #26
0
func run(cmd *cobra.Command, args []string) {
	log.Print("Reading config.toml file")
	err := viper.ReadInConfig()
	if err != nil {
		log.Fatal("Error reading config file: ", err)
	}

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

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

	if migrateFlag {
		migrate(config)
		return
	}

	app, err = gateway.NewApp(config)

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

	app.Serve()
}
Example #27
0
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"))
}
Example #28
0
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 {}
}
Example #29
0
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)
	}
}
Example #30
-1
func init() {
	viper.SetConfigName("conf")
	viper.AddConfigPath(".")
	viper.WatchConfig()
	viper.ReadInConfig()
	viper.Unmarshal(&conf)
	viper.OnConfigChange(func(e fsnotify.Event) {
		if err := viper.Unmarshal(&conf); err != nil {
			log.Println(err.Error())
		} else {
			log.Println("config auto reload!")
		}
	})

	r = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: conf.RedisPass,
	})

	scheduler.Every().Day().At("00:00").Run(func() {
		if time.Now().Day() == 1 {
			length := r.ZCard("Shan8Bot:K").Val()
			if length < 25 {
				return
			}
			i := rand.Int63n(length-25) + 25
			for _, v := range r.ZRangeWithScores("Shan8Bot:K", i, i).Val() {
				log.Println("add 100K for ", v.Member)
				r.ZIncrBy("Shan8Bot:K", 100, v.Member.(string))
			}
		}
	})
}