// Homework 47, problem 2: Settings from the environment. (solution) // // Run with: go run exercises/47/homework/solutions/02-greeter-config.go // or: go run exercises/47/homework/solutions/02-greeter-config.go -name Keiko -times 3 package main import ( "flag" "fmt" "os" "strconv" ) type config struct { name string times int } // envOr returns the environment variable called name, or fallback when it is // not set. func envOr(name, fallback string) string { value, ok := os.LookupEnv(name) if !ok { return fallback } return value } // envInt is envOr for a whole number. A value that is not one is an error. func envInt(name string, fallback int) (int, error) { value, ok := os.LookupEnv(name) if !ok { return fallback, nil } n, err := strconv.Atoi(value) if err != nil { return 0, fmt.Errorf("%s must be a whole number, not %q", name, value) } return n, nil } func loadConfig() (config, error) { times, err := envInt("GREET_TIMES", 1) if err != nil { return config{}, err } var cfg config flag.StringVar(&cfg.name, "name", envOr("GREET_NAME", "friend"), "who to greet (env GREET_NAME)") flag.IntVar(&cfg.times, "times", times, "how many times, from 1 to 10 (env GREET_TIMES)") flag.Parse() if cfg.times < 1 || cfg.times > 10 { return config{}, fmt.Errorf("times must be from 1 to 10, not %d", cfg.times) } return cfg, nil } func main() { cfg, err := loadConfig() if err != nil { fmt.Fprintln(os.Stderr, "Error:", err) os.Exit(1) } for range cfg.times { fmt.Printf("Hello, %s!\n", cfg.name) } }