Exemple #1
0
// Simple example always updates the config when file changes are detected.
func simple(parser *args.ArgParser) args.WatchCancelFunc {
	// Get our current config
	appConf := parser.GetOpts()
	configFile := appConf.String("config-file")

	// Watch the file every time.Second and call func(err error){} when the file is modified
	cancelWatch, err := args.WatchFile(configFile, time.Second, func(err error) {
		if err != nil {
			fmt.Printf("Watch Error %s\n", err.Error())
			return
		}

		// You can safely ignore the returned Options{} object here.
		// the next call to GetOpts() from within the handler will
		// pick up the newly parsed config
		appConf, err = parser.FromINIFile(configFile)
		if err != nil {
			fmt.Printf("Failed to load updated config - %s\n", err.Error())
			return
		}
	})

	if err != nil {
		fmt.Printf("Unable to start watch '%s' -  %s", configFile, err.Error())
	}
	return cancelWatch
}
Exemple #2
0
func listChickens(subParser *args.ArgParser, data interface{}) int {
	opts := subParser.GetOpts()

	shared := data.(*SharedStruct)
	req, err := http.NewRequest("GET", joinUrl(shared, "chickens"), nil)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return 1
	}
	resp, err := sendRequest(opts, req, nil)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return 1
	}
	fmt.Println(resp)
	return 0
}
Exemple #3
0
// The complex example allows a user to write the config file multiple times, possibly applying edits incrementally.
// When the user is ready for the application to apply the config changes, modify the 'version' value and the
// new config is applied.
func complex(parser *args.ArgParser) args.WatchCancelFunc {
	// Get our current config
	appConf := parser.GetOpts()
	configFile := appConf.String("config-file")

	// Watch the file every time.Second and call func(err error){} when the file is modified
	cancelWatch, err := args.WatchFile(configFile, time.Second, func(err error) {
		if err != nil {
			fmt.Printf("Watch Error %s\n", err.Error())
			return
		}

		// load the file from disk
		content, err := args.LoadFile(configFile)
		if err != nil {
			fmt.Printf("Failed to load config - %s\n", err.Error())
		}

		// Parse the file contents
		newConfig, err := parser.ParseINI(content)
		if err != nil {
			fmt.Printf("Failed to update config - %s\n", err.Error())
			return
		}

		// Only "Apply" the newConfig when the version changes
		if appConf.Int("version") != newConfig.Int("version") {
			// Apply the newConfig values to the parser rules
			appConf, err = parser.Apply(newConfig)
			if err != nil {
				fmt.Printf("Probably a type cast error - %s\n", err.Error())
				return
			}
		}
	})
	if err != nil {
		log.Fatal(fmt.Sprintf("Failed to watch '%s' -  %s", configFile, err.Error()))
	}
	return cancelWatch
}