// Homework 48, problem 2: A thin main. (solution) // // Run from the module folder: // cd exercises/48/homework/solutions/02-thin-main // go run ./cmd/convert 100 // go run ./cmd/convert -to c 212 // Test with: go test ./... package main import ( "errors" "flag" "fmt" "io" "os" "strconv" ) func main() { err := run(os.Args[1:], os.Stdout) if err != nil { fmt.Fprintln(os.Stderr, "convert:", err) os.Exit(1) } } // run does the work. It writes the result to out, and returns every problem // as an error for main to print. func run(args []string, out io.Writer) error { flags := flag.NewFlagSet("convert", flag.ExitOnError) to := flags.String("to", "f", "convert to c (Celsius) or f (Fahrenheit)") flags.Parse(args) if flags.NArg() != 1 { return errors.New("give one temperature, like 21.5") } value, err := strconv.ParseFloat(flags.Arg(0), 64) if err != nil { return fmt.Errorf("%q is not a number", flags.Arg(0)) } switch *to { case "f": fmt.Fprintf(out, "%.1f C is %.1f F\n", value, value*9/5+32) case "c": fmt.Fprintf(out, "%.1f F is %.1f C\n", value, (value-32)*5/9) default: return fmt.Errorf("-to must be c or f, not %q", *to) } return nil }