// Homework 48, problem 2: A thin main. // // All the work happens in main, which prints errors and exits in three places. // Nothing here can be tested. Change it so that: // - the work moves to run(args []string, out io.Writer) error // - run reads its flags with flag.NewFlagSet, from args // - run writes its result to out, and returns every problem as an error // - main calls run(os.Args[1:], os.Stdout); if it gets an error, it prints // "convert: " and the error to stderr, and exits with code 1 // Then write tests for run in main_test.go. // // Run from the module folder: // cd exercises/48/homework/02-thin-main // go run ./cmd/convert 100 // go run ./cmd/convert -to c 212 // Test with: go test ./... package main import ( "flag" "fmt" "os" "strconv" ) func main() { to := flag.String("to", "f", "convert to c (Celsius) or f (Fahrenheit)") flag.Parse() if flag.NArg() != 1 { fmt.Fprintln(os.Stderr, "convert: give one temperature, like 21.5") os.Exit(1) } value, err := strconv.ParseFloat(flag.Arg(0), 64) if err != nil { fmt.Fprintf(os.Stderr, "convert: %q is not a number\n", flag.Arg(0)) os.Exit(1) } switch *to { case "f": fmt.Printf("%.1f C is %.1f F\n", value, value*9/5+32) case "c": fmt.Printf("%.1f F is %.1f C\n", value, (value-32)*5/9) default: fmt.Fprintf(os.Stderr, "convert: -to must be c or f, not %q\n", *to) os.Exit(1) } }