48. Structuring a larger program — Homework solutions

The solutions are in exercises/48/homework/solutions/, one folder each, with the same names as the starters. cd into a folder, and run its commands from there. Go back up to go-work afterwards with cd ../../../../.. from a solution, or cd ../../../.. from a starter.

Problem 1 — Word tools

Problem. Move the word functions out of package main into a package of their own, and add a second program that uses the same package.

How to think about it. Three steps. First, move the code: the two functions and the text go into internal/words/words.go, with capital letters, because cmd/topwords is another package now. The package is called words, so the names inside can be short: words.Count reads better than words.CountWords. Second, main imports wordtools/internal/words, the module name then the folders, and calls them. Run it, and the output must not change. Third, the new program gets its own folder under cmd, because a folder is one package and holds only one main.

Worked solution. internal/words/words.go has the two old functions with new names, and these:

// Sample is the text that both programs use.
const Sample = "the quick cat sat on the mat and the dog sat on the cat"
// Longest returns the longest word in text. When two are equally long, the
// first one wins. A text with no words gives "".
func Longest(text string) string {
    longest := ""
    for _, word := range strings.Fields(text) {
        if len(word) > len(longest) {
            longest = word
        }
    }
    return longest
}

cmd/topwords/main.go is now only this:

import (
    "fmt"

    "wordtools/internal/words"
)

func main() {
    counts := words.Count(words.Sample)
    for _, word := range words.Top(counts, 3) {
        fmt.Printf("%-5s %d\n", word, counts[word])
    }
}

and cmd/longest/main.go, with the same imports:

func main() {
    word := words.Longest(words.Sample)
    fmt.Printf("Longest word: %s (%d letters)\n", word, len(word))
}

Both programs:

go run ./cmd/topwords
the   4
cat   2
on    2

go run ./cmd/longest
Longest word: quick (5 letters)

cat, on and sat all appear twice. Top sorts equal counts A to Z, so sat is the one left out.

Common mistakes.

  • Keeping the lower case names in the new package. main then stops with undefined: words.countWords, because a lower case name is private to its package.
  • Naming a variable words in main, as in words := words.Top(counts, 3). The variable hides the package for the rest of the function, and the next words. call fails. Pick another name, such as word or top.
  • Putting longest.go, with a second func main, next to main.go in cmd/topwords. Go stops with main redeclared in this block. Each program needs its own folder.
  • Running go run cmd/longest without ./. Go looks in the standard library, and the error contains is not in std.

Problem 2 — A thin main

Problem. Move the work out of main into run(args, out) error, and test it.

How to think about it. Go through the old main line by line and ask: does this need the real world? Reading os.Args, writing to os.Stdout and os.Stderr, and calling os.Exit do. Everything else moves to run, with three changes. The flags come from a flag.NewFlagSet, parsed from args. fmt.Printf becomes fmt.Fprintf(out, ...). Each fmt.Fprintln(os.Stderr, ...) and os.Exit(1) pair becomes one return with an error. The convert: in front moves to main, so it is written once.

For the tests, a bytes.Buffer is the out. A table of arguments and the expected output covers the good cases. A list of arguments that must fail covers the rest.

Worked solution.

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
}

main_test.go:

func TestRun(t *testing.T) {
    tests := []struct {
        args []string
        want string
    }{
        {[]string{"100"}, "100.0 C is 212.0 F\n"},
        {[]string{"-to", "f", "0"}, "0.0 C is 32.0 F\n"},
        {[]string{"-to", "c", "212"}, "212.0 F is 100.0 C\n"},
        // "--" ends the flags, so that -40 is read as a number.
        {[]string{"--", "-40"}, "-40.0 C is -40.0 F\n"},
    }
    for _, tt := range tests {
        var out bytes.Buffer
        err := run(tt.args, &out)
        if err != nil {
            t.Errorf("run(%q) gave error %v", tt.args, err)
            continue
        }
        if out.String() != tt.want {
            t.Errorf("run(%q) wrote %q, want %q", tt.args, out.String(), tt.want)
        }
    }
}

func TestRunErrors(t *testing.T) {
    tests := [][]string{
        {},
        {"1", "2"},
        {"warm"},
        {"-to", "k", "5"},
    }
    for _, args := range tests {
        var out bytes.Buffer
        err := run(args, &out)
        if err == nil {
            t.Errorf("run(%q) gave no error", args)
        }
        if out.Len() != 0 {
            t.Errorf("run(%q) wrote %q after an error", args, out.String())
        }
    }
}

The program works as before:

go run ./cmd/convert -to c 212
212.0 F is 100.0 C

go run ./cmd/convert warm
convert: "warm" is not a number
exit status 1

go test ./...
ok      tempconv/cmd/convert    0.003s

The tests do not check a bad flag such as -x. With flag.ExitOnError, the flag set calls os.Exit itself, which would end the whole test run. That is a fair trade for a small tool: the flag package's own messages are already right.

Common mistakes.

  • Keeping flag.String and flag.Parse. They read os.Args, not args, so every test sees the test program's own command line. And the second call to run crashes with flag redefined: to.
  • A test case {"-to", "f", "-40"}. The flag set reads -40 as a flag, prints flag provided but not defined: -40, and exits the test run. -- ends the flags, which is also how a user would type it: go run ./cmd/convert -- -40.
  • Leaving a fmt.Println in run. The test passes out, but the text goes to the screen, and the test sees an empty buffer.
  • Writing "convert: " into the error messages as well as in main. The message then says convert: convert: ....

Problem 3 — Pass it in

Problem. Replace the package-level variables with a struct made by New, so that each user of the package has its own count.

How to think about it. First, see the problem. One of the starter's tests fails:

--- FAIL: TestSecondVisit (0.00s)
    web_test.go:45: got "Hi! You are visitor number 3.\n", want "Hi! You are visitor number 2.\n"

TestFirstVisit already counted one visit, and the count is one variable for the whole program, so the second test starts at 1, not 0. Each test would have to reset it, and remember to.

The fix follows the notes server. Every package-level variable becomes a field of App. Setup becomes New, which returns a new App. Every function that used the variables becomes a method with the receiver a *App, and writes a.visits and a.logger. The handler is registered as a.handleHome. The receiver must be a pointer: the App holds a mutex, which must never be copied, and the count must change in the one real App.

Worked solution.

// App holds what the handlers need. Make one with New.
type App struct {
    mu       sync.Mutex // protects visits
    visits   int
    logger   *slog.Logger
    greeting string
}

// New returns an App that logs to logger, and starts every reply with
// greeting.
func New(logger *slog.Logger, greeting string) *App {
    return &App{logger: logger, greeting: greeting}
}

// Handler returns the routes.
func (a *App) Handler() http.Handler {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /{$}", a.handleHome)
    return mux
}

func (a *App) handleHome(w http.ResponseWriter, r *http.Request) {
    n := a.nextVisit()
    a.logger.Info("visit", "number", n)
    fmt.Fprintf(w, "%s You are visitor number %d.\n", a.greeting, n)
}

// nextVisit adds one to the count and returns it.
func (a *App) nextVisit() int {
    a.mu.Lock()
    defer a.mu.Unlock()

    a.visits++
    return a.visits
}

visits starts at 0 and the mutex starts unlocked, so New only fills in the other two. In main.go, web.Setup(logger, *greeting) becomes app := web.New(logger, *greeting), and the server's Handler is app.Handler(). In the tests, each one makes its own:

func TestTwoApps(t *testing.T) {
    first := New(quietLogger(), "A").Handler()
    second := New(quietLogger(), "B").Handler()

    visit(first)
    visit(first)
    got := visit(second)
    want := "B You are visitor number 1.\n"
    if got != want {
        t.Errorf("got %q, want %q", got, want)
    }
}

Now all three tests pass, in any order:

go test ./...
?       visits/cmd/visits   [no test files]
ok      visits/internal/web 0.004s

Common mistakes.

  • Writing the methods with a value receiver, func (a App) nextVisit() int. Each call works on a copy, so the count never gets past 1, and go vet reports that the call passes lock by value.
  • Keeping var visits int at the top as well as the field. The methods may then use the wrong one without any error. Delete the old variables, and let Go find every place that still used them.
  • Forgetting to change a test, so that it still calls Setup. Go stops with undefined: Setup, which is what you want: the compiler lists every place left to change.

Challenge — A fake store

Problem. Let internal/web take any store with the right methods, and test it with fakes, including one that fails.

How to think about it. Look at what web really calls on the store: List and Add, nothing else. Those two methods, with the same signatures as in store.File, make the interface. It goes in web, the package that uses it. Then change the type of the field and of New's parameter from *store.File to Store. The handlers do not change at all, because they only call the two methods. main does not change either: *store.File has both methods, so it is still accepted.

web no longer needs to import store, so delete that import. The tests can then have a memory store and a failing store, as in the chapter.

Worked solution. In internal/web/web.go:

// Store is what this package needs from a store. store.File has these
// methods, and so do the fakes in the tests.
type Store interface {
    List() []score.Score
    Add(sc score.Score) error
}

// App holds what the handlers need. Make one with New.
type App struct {
    store  Store
    logger *slog.Logger
}

// New returns an App that uses this store and logger.
func New(s Store, logger *slog.Logger) *App {
    return &App{store: s, logger: logger}
}

In internal/web/web_test.go:

// memoryStore keeps scores in a slice. Each test makes its own, so it needs
// no mutex.
type memoryStore struct {
    scores []score.Score
}

func (m *memoryStore) List() []score.Score {
    return slices.Clone(m.scores)
}

func (m *memoryStore) Add(sc score.Score) error {
    m.scores = append(m.scores, sc)
    return nil
}

// failingStore is a store whose Add always fails, like a full disk.
type failingStore struct {
    memoryStore
}

func (f *failingStore) Add(sc score.Score) error {
    return errors.New("disk full")
}

and the new test:

func TestSaveFails(t *testing.T) {
    handler := newTestHandler(&failingStore{})

    response := send(handler, "POST", "/api/scores", `{"player": "Keiko", "points": 40}`)
    if response.Code != http.StatusInternalServerError {
        t.Errorf("status %d, want 500", response.Code)
    }
    if !strings.Contains(response.Body.String(), "could not be saved") {
        t.Errorf("the body is %s", response.Body)
    }
}

newTestHandler makes an App with the given store and a logger to io.Discard. TestAddThenList uses &memoryStore{} in place of the file, and the solution adds TestBadScore, which checks that a player with no name gets 400 and is not saved.

go test ./...
?       scores/cmd/scores   [no test files]
?       scores/internal/score   [no test files]
?       scores/internal/store   [no test files]
ok      scores/internal/web 0.005s

Common mistakes.

  • Declaring the interface in internal/store. It works, but web then imports store only for the interface, and every new method in the store tempts you to add it there. The package that uses it knows best what it needs.
  • Putting every method of store.File in the interface, including ones web never calls. Each fake must then write them all.
  • Giving the fake a value receiver for List and a pointer receiver for Add, then passing memoryStore{} without &. Go stops with an error that ends in memoryStore does not implement Store (method Add has pointer receiver). Pass &memoryStore{}.
  • Writing Add in the fake with another signature, such as Add(sc score.Score) with no error. The fake then does not satisfy Store, and the error says which method is wrong.

Done?

You can now lay out a program as a module with cmd/ and internal/, give each package one job, pass in what it needs, and test each part with fakes. That is everything the final project needs. Go on to the Final project: Expense Tracker, which brings together all of Part 10.