当前位置: 首页>>代码示例>>Golang>>正文


Golang viper.WatchConfig函数代码示例

本文整理汇总了Golang中github.com/spf13/viper.WatchConfig函数的典型用法代码示例。如果您正苦于以下问题:Golang WatchConfig函数的具体用法?Golang WatchConfig怎么用?Golang WatchConfig使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了WatchConfig函数的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

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

示例2: init

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))
			}
		}
	})
}
开发者ID:jqs7,项目名称:Shan8Bot,代码行数:33,代码来源:init.go

示例3: watchConfig

func watchConfig() {
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
		utils.CheckErr(buildSite(true))
		if !viper.GetBool("DisableLiveReload") {
			// Will block forever trying to write to a channel that nobody is reading if livereload isn't initialized
			livereload.ForceRefresh()
		}
	})
}
开发者ID:ridelore,项目名称:hugo,代码行数:11,代码来源:hugo.go

示例4: initConfig

// 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(".nessusControl") // 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 {
		viper.WatchConfig()
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}
开发者ID:kkirsche,项目名称:nessusControl,代码行数:16,代码来源:root.go

示例5: SetupNotificationConfig

func (c *Conf) SetupNotificationConfig(filename string, config NotificationServiceConfig) {
	viperConfig := viper.New()

	c.setupHome(viperConfig, viper.GetString("Home"))
	viperConfig.SetConfigName(filename)

	if err := viperConfig.ReadInConfig(); err != nil {
		log.Printf("Cannot read notification config: %s", err)
	}
	viperConfig.Unmarshal(config)

	viper.OnConfigChange(func(in fsnotify.Event) { viperConfig.ReadInConfig(); viperConfig.Unmarshal(config) })
	viper.WatchConfig()

	c.notificationConfigs = append(c.notificationConfigs, config)
}
开发者ID:RobinUS2,项目名称:indispenso,代码行数:16,代码来源:conf.go

示例6: realMain

func realMain(c *cli.Context) {
	// Create the underlying connection
	bot := ircx.Classic(c.String("server"), c.String("name"))
	bot.Config.MaxRetries = 10
	if usr := c.String("user"); usr != "" {
		bot.Config.User = usr
	}
	bot.Config.Password = c.String("pass")

	channels := strings.Split(c.String("channels"), ",")

	// Create a new bogon
	bogon, err := bogon.New(bot, c.String("name"), channels)
	if err != nil {
		log.Fatalf("Unable to start new bogon: %s", err)
	}

	// Setup & add config
	viper.AutomaticEnv()

	// Add config file if provided
	if cfg := c.String("config"); cfg != "" {
		viper.SetConfigFile(cfg)
		viper.WatchConfig()
		if err := viper.ReadInConfig(); err != nil {
			log.Fatalf("Unable to read config: %s", err)
		}
	}

	// Add viper provider
	config.RegisterProvider(viperprovider.V{})

	// Set up commands
	if err := commandSetup(bogon, c); err != nil {
		log.Fatalf("error setting up commands: %s", err)
	}

	if cfg := c.String("admin"); cfg != "" {
		bogon.AdminSocket(cfg)
	}

	// Connect!
	if err := bogon.Connect(); err != nil {
		log.Fatalf("Unable to connect: %s", err)
	}
	bogon.Start()
}
开发者ID:nickvanw,项目名称:bogon,代码行数:47,代码来源:main.go

示例7: startup

func startup() error {

	var config lib.Config

	if err := viper.Unmarshal(&config); err != nil {
		return err
	}

	serverAndPort := fmt.Sprintf("%s:%d", serverInterface, serverPort)

	if config.Feed.Link == "" {
		config.Feed.Link = "http://" + serverAndPort
	}

	if config.Feed.MaxItems <= 0 {
		config.Feed.MaxItems = 10
	}

	// enable live reloading of config
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config", e.Name, "changed ...")
		if err := viper.Unmarshal(&config); err != nil {
			fmt.Println("error: Failed to reload config: ", err)
			return
		}
		shutdownIfNeededAndStart(config)
	})

	viper.WatchConfig()

	shutdownIfNeededAndStart(config)

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		w.Header().Set("Content-Type", "application/rss+xml; charset=utf-8")
		fmt.Fprintf(w, app().GetFeed())
	})

	fmt.Printf("\nStarting server on http://%s ...\n\n", serverAndPort)

	graceful.Run(serverAndPort, 10*time.Second, mux)

	app().Shutdown()

	fmt.Println("\nStopped ...")
	return nil
}
开发者ID:bep,项目名称:alfn,代码行数:47,代码来源:root.go

示例8: initByConfigFile

func initByConfigFile() {
	log.Println("init params by configfile..")
	viper.SetConfigName("gate-conf")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".") // optionally look for config in the working directory
	viper.AddConfigPath("$HOME/.seckilling/")
	viper.AddConfigPath("/etc/seckilling/")

	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		log.Panicf("Fatal error config file: %s \n", err)
	}

	if viper.GetBool("watch") {
		viper.WatchConfig()
	}
	viper.OnConfigChange(func(e fsnotify.Event) {
		log.Println("Config file changed:", e.Name)
	})

	log.Printf("loading config %s \n", viper.ConfigFileUsed())
}
开发者ID:Dataman-Cloud,项目名称:seckilling,代码行数:22,代码来源:configuration.go

示例9: initConfig

func initConfig() {
	// defaults
	viper.SetDefault("AdminLocation", "/admin/") // TODO : some helper to convert strings to paths ? ie: path("admin") -> "/admin/"
	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:doesntgolf,项目名称:topiary,代码行数:24,代码来源:config.go

示例10: main


//.........这里部分代码省略.........
		cli.BoolFlag{
			Name:  "debug, d",
			Usage: "if present, all debug messages will be shown",
		},
	}

	hiddenFlags := make([]cli.Flag, len(viper.AllKeys()))
	for i, configValue := range viper.AllKeys() {
		hiddenFlags[i] = cli.StringFlag{
			Name:   configValue,
			Hidden: true,
		}
	}
	app.Flags = append(app.Flags, hiddenFlags...)

	app.Action = func(c *cli.Context) error {
		if c.Bool("debug") {
			logrus.SetLevel(logrus.InfoLevel)
		}

		for _, configValue := range viper.AllKeys() {
			if c.GlobalIsSet(configValue) {
				if strings.Contains(c.String(configValue), ",") {
					viper.Set(configValue, strings.Split(c.String(configValue), ","))
				} else {
					viper.Set(configValue, c.String(configValue))
				}
			}
		}

		viper.SetConfigFile(c.String("config"))
		if err := viper.ReadInConfig(); err != nil {
			logrus.WithFields(logrus.Fields{
				"file":  c.String("config"),
				"error": err.Error(),
			}).Warnln("An error occurred while reading the configuration file. Using default configuration...")
			if _, err := os.Stat(c.String("config")); os.IsNotExist(err) {
				createConfigWhenNotExists()
			}
		} else {
			if duplicateErr := bot.CheckForDuplicateAliases(); duplicateErr != nil {
				logrus.WithFields(logrus.Fields{
					"issue": duplicateErr.Error(),
				}).Fatalln("An issue was discoverd in your configuration.")
			}
			createNewConfigIfNeeded()
			viper.WatchConfig()
		}

		if c.GlobalIsSet("server") {
			viper.Set("connection.address", c.String("server"))
		}
		if c.GlobalIsSet("port") {
			viper.Set("connection.port", c.String("port"))
		}
		if c.GlobalIsSet("username") {
			viper.Set("connection.username", c.String("username"))
		}
		if c.GlobalIsSet("password") {
			viper.Set("connection.password", c.String("password"))
		}
		if c.GlobalIsSet("channel") {
			viper.Set("defaults.channel", c.String("channel"))
		}
		if c.GlobalIsSet("cert") {
			viper.Set("connection.cert", c.String("cert"))
		}
		if c.GlobalIsSet("key") {
			viper.Set("connection.key", c.String("key"))
		}
		if c.GlobalIsSet("accesstokens") {
			viper.Set("connection.access_tokens", c.String("accesstokens"))
		}
		if c.GlobalIsSet("insecure") {
			viper.Set("connection.insecure", c.Bool("insecure"))
		}

		if err := DJ.Connect(); err != nil {
			logrus.WithFields(logrus.Fields{
				"error": err.Error(),
			}).Fatalln("An error occurred while connecting to the server.")
		}

		if viper.GetString("defaults.channel") != "" {
			defaultChannel := strings.Split(viper.GetString("defaults.channel"), "/")
			DJ.Client.Do(func() {
				DJ.Client.Self.Move(DJ.Client.Channels.Find(defaultChannel...))
			})
		}

		DJ.Client.Do(func() {
			DJ.Client.Self.SetComment(viper.GetString("defaults.comment"))
		})
		<-DJ.KeepAlive

		return nil
	}

	app.Run(os.Args)
}
开发者ID:GabrielPlassard,项目名称:mumbledj,代码行数:101,代码来源:main.go

示例11: EnableAutoUpdate

func (c *Conf) EnableAutoUpdate() {
	viper.OnConfigChange(func(in fsnotify.Event) { c.Update() })
	viper.WatchConfig()
}
开发者ID:RobinUS2,项目名称:indispenso,代码行数:4,代码来源:conf.go

示例12: Run

func Run() {

	viper.SetConfigName("config")
	viper.AddConfigPath("/root/work/src/vishnu")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.WatchConfig()
	Dictionnary := viper.Get("Dictionnary")
	dlign, err := ioutil.ReadFile(Dictionnary.(string))
	check(err)
	fmt.Print(string(dlign))
	rp1, err := regexp.Compile(".+:")
	users := rp1.FindAllString(string(dlign), -1) // type id []string
	fmt.Println(users)
	rp2, err := regexp.Compile(":.+")
	passwords := rp2.FindAllString(string(dlign), -1) // type id []string
	fmt.Println(passwords)
	// TODO : Must try/except for every usercleaned/passworcleaned my ssh connection
	for j := 0; j <= len(users)-1; j++ {
		usercleaned := strings.TrimSuffix(users[j], ":")
		passwordcleaned := strings.TrimPrefix(passwords[j], ":")
		fmt.Println(usercleaned)
		fmt.Println(passwordcleaned)
	}
	sshConfig := &ssh.ClientConfig{
		User: usercleaned,
		Auth: []ssh.AuthMethod{
			ssh.Password(passwordcleaned),
		},
	}
	//TODO : Must fix this fixed ip
	client := &SSHClient{
		Config: sshConfig,
		Host:   "127.0.0.1",
		Port:   22,
	}

	cmdlsroot := &SSHCommand{
		Path:   "ls -l $LC_DIR",
		Env:    []string{"LC_DIR=/"},
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
	cmdlsb := &SSHCommand{
		Path:   "lsb_release -a",
		Env:    []string{"LC_DIR=/"},
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}

	cmduname := &SSHCommand{
		Path:   "uname -r",
		Env:    []string{"LC_DIR=/"},
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
	cmdps := &SSHCommand{
		Path:   "ps faux",
		Env:    []string{"LC_DIR=/"},
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}

	fmt.Printf("Running command: %s\n", cmdlsb.Path)
	if err := client.RunCommand(cmdlsb); err != nil {
		fmt.Fprintf(os.Stderr, "command run error: %s\n", err)
		os.Exit(1)
	}
	fmt.Printf("Running command: %s\n", cmdlsroot.Path)
	if err := client.RunCommand(cmdlsroot); err != nil {
		fmt.Fprintf(os.Stderr, "command run error: %s\n", err)
		os.Exit(1)
	}
	fmt.Printf("Running command: %s\n", cmduname.Path)
	if err := client.RunCommand(cmduname); err != nil {
		fmt.Fprintf(os.Stderr, "command run error: %s\n", err)
		os.Exit(1)
	}
	fmt.Printf("Running command: %s\n", cmdps.Path)
	if err := client.RunCommand(cmdps); err != nil {
		fmt.Fprintf(os.Stderr, "command run error: %s\n", err)
		os.Exit(1)
	}

}
开发者ID:r3dlight,项目名称:vishnu,代码行数:91,代码来源:sshme.go


注:本文中的github.com/spf13/viper.WatchConfig函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。