48. Structuring a larger program

The notes server at the end of Chapter 47 works, and it is ready to ship. It is also one main.go of more than three hundred lines, in one package. Everything can see everything: any function can change the package-level variables store and pages, and the tests of Chapter 45 had to replace such a variable before each test. A program that keeps growing like that gets hard to read, hard to test, and easy to break.

Chapter 25 showed how to split code into packages. This chapter shows how to split a real program: which packages to make, what goes where, and how the parts get what they need without package-level variables. It splits the notes server, and adds no new features. The final project, the Expense Tracker, uses exactly this layout.

One module, several programs

A module can hold more than one program. Each program is a package main, and since a folder is one package, each one needs a folder of its own. By convention, those folders are inside a folder called cmd, and the packages that the programs share are inside a folder called internal. This is exercises/48/01-layout/:

01-layout/
    go.mod
    cmd/
        hello/
            main.go
        goodbye/
            main.go
    internal/
        greet/
            greet.go
            greet_test.go

go.mod names the module layout. internal/greet/greet.go is an ordinary package:

// Hello returns a greeting for name.
func Hello(name string) string {
    return "Hello, " + clean(name) + "!"
}

// Goodbye returns a farewell for name.
func Goodbye(name string) string {
    return "Goodbye, " + clean(name) + "."
}

clean is a private helper that trims the name, and uses friend when it is empty. cmd/hello/main.go imports the package with the module name, then the folders:

import (
    "flag"
    "fmt"

    "layout/internal/greet"
)

func main() {
    name := flag.String("name", "", "who to greet")
    flag.Parse()

    fmt.Println(greet.Hello(*name))
}

cmd/goodbye/main.go is the same, with greet.Goodbye. Your own imports go in a separate group under the standard library ones, which makes them easy to spot.

Every command runs from the top folder of the module, the one with go.mod. To run a program, give go run the path of its folder, starting with ./:

cd exercises/48/01-layout
go run ./cmd/hello -name Keiko
Hello, Keiko!

go run ./cmd/goodbye
Goodbye, friend.

The ./ matters. Without it, go run cmd/hello looks for a package called cmd/hello in the standard library, and stops with an error containing is not in std.

./... means "this folder and every folder below it", so one command tests, or checks, every package in the module:

go test ./...
?       layout/cmd/goodbye  [no test files]
?       layout/cmd/hello    [no test files]
ok      layout/internal/greet   0.002s

go vet ./...

The times will be different for you. go build takes the folder of the program too:

go build -o hello.exe ./cmd/hello

Without -o, the .exe is named after the folder, hello.exe. That is one reason to put each program in cmd/<its name>: the folder name becomes the program's name. Go back up to go-work with cd ../../.. when you are done.

What internal means

Chapter 25 showed one wall: a name with a lower case first letter cannot be used outside its package. internal is a second wall, around a group of packages. A package inside a folder called internal can only be imported by code in the folder that holds internal, and the folders below it. Here, that is everything in 01-layout. Code in any other module that tries to import layout/internal/greet is refused with use of internal package layout/internal/greet not allowed.

So the two walls do different jobs:

  • A capital letter lets other packages use a name. greet.Hello must be exported, or cmd/hello could not call it.
  • internal says that those packages are other packages of this program, not of the world. You can rename Hello, or change what it takes, and only code in your own module can be affected, which you can fix in the same change.

Put every package of an application in internal, unless you mean to share it with other people's programs.

Add a third program to exercises/48/01-layout: cmd/both/main.go, which prints both the greeting and the farewell. Run it with go run ./cmd/both.

Splitting the notes server

exercises/48/02-notes/ is the notes server from Chapter 47, split up. It does the same things, with the same settings, but its stylesheet is left out, to keep it short. The module is called notes:

02-notes/
    go.mod
    cmd/
        notes/
            main.go
            main_test.go
            settings.go
    internal/
        note/
            note.go
            note_test.go
        store/
            store.go
            store_test.go
        web/
            web.go
            web_test.go
            templates/
                home.html

Each package has one job, and knows nothing about the jobs of the others:

Package Its job Imports
internal/note The rules: what a valid note is. None of yours.
internal/store Keeping notes in a JSON file, safely from many requests. note
internal/web The page and the JSON list. note
cmd/notes The settings, the logger, starting and stopping the server. All of them

Drawn as a picture, each arrow means "imports":

cmd/notes internal/web internal/store internal/note

The arrows only go down. note is at the bottom, and imports nothing of yours, so it is the easiest to test, and it could be used by a terminal program with no change, as the guestbook package was in the Guestbook project. cmd/notes is at the top, and is the only package that knows all the others. Its job is to connect them.

Arrows that go round in a circle are not allowed at all. If store imported web while web imported store, Go would stop with an error that ends in import cycle not allowed. When two packages seem to need each other, the shared part usually belongs in a third package below both, as note is here.

The rules: internal/note

This package holds the Note type and the check that every new note goes through. This is internal/note/note.go, without its imports:

// MaxLength is the most characters a note can have.
const MaxLength = 200

// Note is one note. The JSON tags give the names used in the file and by the
// API.
type Note struct {
    ID      int       `json:"id"`
    Text    string    `json:"text"`
    Created time.Time `json:"created"`
}

// New trims and checks the text, and returns a note without an ID. The store
// gives it an ID when it is added. The errors are meant for people to read.
func New(text string, created time.Time) (Note, error) {
    text = strings.TrimSpace(text)
    if text == "" {
        return Note{}, errors.New("the note is empty")
    }
    if utf8.RuneCountInString(text) > MaxLength {
        return Note{}, fmt.Errorf("the note can have at most %d characters", MaxLength)
    }
    return Note{Text: text, Created: created}, nil
}

New takes the time as an argument, and does not call time.Now itself. That keeps it predictable, so note_test.go can check its result with ==.

The package name is part of every name outside it: note.Note, note.New, note.MaxLength. So the names inside it are short, and do not repeat the package name. note.NewNote would say "note" twice.

The file: internal/store

internal/store/store.go is the noteStore from Chapter 47, renamed:

// File is a store saved to a JSON file. Make one with Open.
type File struct {
    mu       sync.Mutex // protects notes and the file
    filename string
    notes    []note.Note
}

Outside the package, it reads store.File and store.Open(filename). It has two methods, All() []note.Note and Add(n note.Note) (note.Note, error), with the same bodies as before. The fields have lower case names, so no other package can touch the notes without going through the methods and their mutex. Chapter 44 made that a rule that you had to remember. Now Go enforces it.

The web: internal/web

In Chapter 47, the handlers used two package-level variables, store and pages. A package-level variable is shared by everything in the program, and only one of it exists. In a test, you have to set it before each test, and remember to. Two servers with different stores in one program are impossible.

internal/web has no package-level variables, apart from the embedded template, which never changes. Everything the handlers need is in a struct, and they are its methods. This is the top of internal/web/web.go:

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

// New reads the embedded template and returns an App that uses this store and
// logger. The version is shown at the bottom of the page.
func New(store Store, logger *slog.Logger, version string) (*App, error) {
    page, err := template.ParseFS(templateFiles, "templates/home.html")
    if err != nil {
        return nil, err
    }
    return &App{store: store, logger: logger, version: version, page: page}, nil
}

// Handler returns every route, wrapped so that each request is logged.
func (a *App) Handler() http.Handler {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /{$}", a.handleHome)
    mux.HandleFunc("POST /notes", a.handleAdd)
    mux.HandleFunc("GET /api/notes", a.handleList)
    return a.logRequests(mux)
}

This is called passing dependencies: whatever a part depends on, its store, its logger, its settings, is handed to it through New, and not found in a global variable. Look at what New takes, and you know everything the web side uses. Nothing is hidden.

a.handleHome is a method used as a value. It is a function that already knows its a, so the router can call it like any handler, and inside it, a.store and a.logger are there:

func (a *App) handleAdd(w http.ResponseWriter, r *http.Request) {
    n, err := note.New(r.FormValue("text"), time.Now())
    if err != nil {
        a.showHome(w, http.StatusBadRequest, err.Error())
        return
    }

    added, err := a.store.Add(n)
    if err != nil {
        a.logger.Error("save failed", "err", err)
        http.Error(w, "The note could not be saved.", http.StatusInternalServerError)
        return
    }
    a.logger.Info("note added", "id", added.ID)

    http.Redirect(w, r, "/", http.StatusSeeOther)
}

Handler returns an http.Handler, so cmd/notes can put it in its http.Server, and a test can call it with httptest, as in Chapter 45.

Interfaces where they are used

The field store in App does not have the type *store.File. It has the type Store, an interface that internal/web declares for itself:

// Store is what the web side needs from a store. store.File has these
// methods, and so does the memory store in the tests.
type Store interface {
    All() []note.Note
    Add(n note.Note) (note.Note, error)
}

Chapter 29 showed that a type satisfies an interface just by having its methods. It does not have to say so. store.File has All and Add, so a *store.File can be passed to web.New, although internal/store has never heard of web.Store. That is why web does not need to import store at all.

The interface is declared where it is used, in the package that needs a store, and not in the package that has one. It lists only the methods that web calls. If store.File gets a Delete method later, web.Store does not change, and nothing in web has to. A small interface is also easy to fake.

That is the payoff. internal/web/web_test.go has two stores of its own, with no file at all:

// memoryStore keeps notes in a slice. It has the methods of Store, so the
// tests need no file. Each test makes its own, so it needs no mutex.
type memoryStore struct {
    notes []note.Note
}

func (m *memoryStore) All() []note.Note {
    return slices.Clone(m.notes)
}

func (m *memoryStore) Add(n note.Note) (note.Note, error) {
    n.ID = len(m.notes) + 1
    m.notes = append(m.notes, n)
    return n, nil
}

// brokenStore is a memoryStore whose Add always fails, like a full disk. It
// embeds memoryStore for All, and has its own Add.
type brokenStore struct {
    memoryStore
}

func (b *brokenStore) Add(n note.Note) (note.Note, error) {
    return note.Note{}, errors.New("disk full")
}

A store that stands in for the real one in a test is called a fake. brokenStore uses embedding from Chapter 29: it gets All from memoryStore, and its own Add wins over the embedded one. With it, a test can check what happens when saving fails, which is very hard to arrange with a real disk:

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

    response := postNote(handler, "buy milk")
    if response.Code != http.StatusInternalServerError {
        t.Errorf("status = %d, want 500", response.Code)
    }
}

newTestHandler calls New with the given store and a logger that writes to io.Discard, a writer that throws everything away, so the test output stays clean. postNote sends the form with httptest. Each test makes its own App, so no test can change what another one sees.

A package that uses an interface may still import the package of the real type for other things. The Expense Tracker's web package imports store to compare errors with store.ErrNotFound. That is fine, as long as the arrow points one way: store never imports web.

A thin main

The last package is cmd/notes. Its job is to connect the parts, and it does as little as possible in main itself:

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    err := run(ctx, os.Args[1:], os.Stdout)
    stop()

    if err != nil {
        fmt.Fprintln(os.Stderr, "notes:", err)
        os.Exit(1)
    }
}

main does the things that only make sense in a real program: it reads the real command line, writes to the real standard output, catches Ctrl+C, and exits with a code. All the rest is in run, which gets those things as arguments: a context, the arguments without the program's name, and an io.Writer to print to. A test can call run with its own values. run begins:

func run(ctx context.Context, args []string, out io.Writer) error {
    flags := flag.NewFlagSet("notes", flag.ExitOnError)
    addr := flags.String("addr", envOr("NOTES_ADDR", "localhost:8080"),
        "address to listen on (env NOTES_ADDR)")
    dataFile := flags.String("file", envOr("NOTES_FILE", "notes.json"),
        "file to keep the notes in (env NOTES_FILE)")
    logLevel := flags.String("log-level", envOr("NOTES_LOG_LEVEL", "info"),
        "debug, info, warn or error (env NOTES_LOG_LEVEL)")
    logFormat := flags.String("log-format", envOr("NOTES_LOG_FORMAT", "text"),
        "text or json (env NOTES_LOG_FORMAT)")
    showVersion := flags.Bool("version", false, "print the version and stop")
    flags.Parse(args)

    if *showVersion {
        fmt.Fprintln(out, "notes", version)
        return nil
    }

The flags are in a flag.NewFlagSet from Chapter 32, parsed from args. flag.String and flag.Parse use one set that belongs to the whole program, which is a package-level variable too: a test that called run twice would define -addr twice, and the program would crash with the message flag redefined: addr. A set of its own for each call avoids that.

The rest of run connects the parts, in the order of the arrows, bottom first:

logger, err := newLogger(*logFormat, *logLevel)
if err != nil {
    return err
}
notes, err := store.Open(*dataFile)
if err != nil {
    return fmt.Errorf("could not load the notes: %w", err)
}
app, err := web.New(notes, logger, version)
if err != nil {
    return fmt.Errorf("could not read the template: %w", err)
}

web.New(notes, ...) is where the real store goes in. Then run makes the http.Server with the four time limits, and hands it to serve, which holds the clean-stop code from Chapter 47. envOr, parseLevel and newLogger are in a second file, cmd/notes/settings.go. A package main can have several files, as Chapter 25 showed, and a long one should.

Because run takes its arguments and its writer, cmd/notes/main_test.go can test it:

func TestVersion(t *testing.T) {
    var out bytes.Buffer
    err := run(context.Background(), []string{"-version"}, &out)
    if err != nil {
        t.Fatalf("run gave error %v", err)
    }
    if out.String() != "notes dev\n" {
        t.Errorf("run printed %q, want \"notes dev\\n\"", out.String())
    }
}

A bytes.Buffer is an io.Writer that keeps what is written to it, so the test can read what run printed. A second test checks that a bad -log-format, a bad -log-level and a broken data file each make run return an error.

Running it

Everything runs from the module's top folder:

cd exercises/48/02-notes
go vet ./...
go test ./...
ok      notes/cmd/notes 0.015s
ok      notes/internal/note 0.004s
ok      notes/internal/store    0.006s
ok      notes/internal/web  0.011s

go run ./cmd/notes
time=2026-11-26T10:20:31.118+07:00 level=INFO msg="server starting" addr=localhost:8080 file=notes.json notes=0 version=dev

To test only one package, name its folder: go test ./internal/web. To ship it, build the program's folder, with the version as in Chapter 47:

go build -ldflags "-s -w -X main.version=1.0.0" -o notes.exe ./cmd/notes

-X main.version still works: whatever the folder, a program's package is always called main. Go back up to go-work with cd ../../.. when you are done.

In exercises/48/02-notes/internal/web/web.go, change http.StatusInternalServerError in handleAdd to http.StatusBadRequest, and run go test ./.... Only one test fails, and only in one package. Put it back.

How to split your own programs

There is no single right layout, but these habits will take you a long way:

  • Start with one package. Split when a file gets long, or when you want to test a part on its own. A twenty-line program needs no internal.
  • Split by job, not by kind. note, store and web each do one thing. Folders called models, helpers or utils collect unrelated code, and soon everything imports them.
  • Keep the rules at the bottom. The package with the rules imports nothing of yours, and knows nothing about files, the web or the command line.
  • Pass dependencies in. No package-level variables for things that change, or that a test would want to replace. Put them in a struct made by New.
  • Declare interfaces where they are used, with only the methods that are called.
  • Keep main thin. It reads the real world, calls run, and exits. run can be tested.

The final project builds the Expense Tracker this way, with one program, cmd/expenses, and three packages: internal/expense for the rules, internal/store for the file, and internal/web for the page and the API.

Homework

Each homework is a folder with its own go.mod, in exercises/48/homework/. cd into it, and run the commands from there: go run ./cmd/<name>, go test ./... and go vet ./.... Each starter runs as it is.

Problem 1 — Word tools

Folder: exercises/48/homework/01-word-tools/. cmd/topwords/main.go counts words and prints the top three, all in package main. Move countWords and topWords into internal/words, as Count and Top, and the text as Sample, so that main only calls them and prints. Then add a second program, cmd/longest, that prints the longest word in the same text, with a new function words.Longest.

Problem 2 — A thin main

Folder: exercises/48/homework/02-thin-main/. cmd/convert/main.go converts temperatures, and prints errors and exits in three places. Move the work to run(args []string, out io.Writer) error, with a flag.NewFlagSet, so that main only calls run, and prints convert: and the error if there is one. Then write tests for run in main_test.go: some that convert, and some that must give an error.

Problem 3 — Pass it in

Folder: exercises/48/homework/03-pass-it-in/. Run go test ./... first: one test fails, because both tests share one visitor count, a package-level variable in internal/web/web.go. Replace the variables with the fields of a struct App, made by New(logger, greeting), and make the handler and its helper methods. Update the tests and cmd/visits/main.go, and add a test that shows two Apps count separately.

Challenge — A fake store

Folder: exercises/48/homework/04-fake-store/. internal/web takes a *store.File, so its test needs a real file, and nothing can test what happens when saving fails. Declare a Store interface in internal/web with only the methods it uses, and let App and New take it. In the test, replace the file store with a memory store, and add a test with a store whose Add always fails: the API must answer 500 with an error.

Stuck or done? Open the homework solutions page.