Learn Go with AI · Free online book

Chapter 6: From Command Line to Web

In short: Chapter 6 turns Tracker into a JSON web API built on Go's standard net/http package. You write the request tests yourself, the AI implements the handlers to make them pass, and you review its diff line by line. You also get one check command for gofmt, go vet, tests and govulncheck.

Tracker works, but only for whoever sits at your terminal. To use it from a phone app, a web page or another program, it needs to speak the language of the web: HTTP. In this chapter, Tracker becomes a small web API: other programs send it requests and get JSON back.

The AI stays the implementer, and it gets a bigger job than in Chapter 5. You’ll write the request tests that say exactly how the API must behave. The AI will build the API from them. Then you’ll review its work the way professionals do: by reading its diff, the exact lines it added and removed.

Before any of that, you’ll make Review faster. You’ve been typing the same checks since Chapter 1. Now you’ll build one command that runs them all, including a new one: a check for known security problems.

It’s the same SURE loop. You Specify with tests, the AI does the typing in Use the AI, and Review and Explain are still yours.

Mission

By the end of this chapter, you’ll have:

Must know

  1. A handler answers requests. In Go, anything with a ServeHTTP(w http.ResponseWriter, r *http.Request) method is an http.Handler. It reads the request r and writes the response to w.
  2. http.ServeMux routes requests by method and path. A pattern like "GET /totals" matches only GET requests to /totals. Requests with the wrong method get 405 Method Not Allowed automatically.
  3. Status codes say how it went. 200 OK means success, 201 Created means something new was added, 400 Bad Request means the client sent something wrong, and 500 Internal Server Error means the server failed.
  4. net/http/httptest tests handlers without a network. httptest.NewRequest builds a request, httptest.NewRecorder records the response, and you call the handler directly. No server, no ports, and the tests run in milliseconds.
  5. encoding/json works on requests too. The same struct tags that wrote expenses.json decode {"category":"Food","cents":350} from a request body into an Expense.

Set up one check command

Install govulncheck

govulncheck is the Go team’s tool for finding known security problems in your code and in the Go version you use. It’s the one tool in this book that doesn’t come with Go. Install it with:

go install golang.org/x/vuln/cmd/govulncheck@latest

It may print a few go: downloading … lines, or nothing at all. No error means it worked.

Check that it runs:

govulncheck -version
Go: go1.27.4
Scanner: govulncheck@v1.10.0
DB: https://vuln.go.dev
DB updated: 2026-11-23 20:05:14 +0000 UTC

Your versions and date will differ.

If you get command not found (or not recognized on Windows), Go installed govulncheck into a folder that isn’t on your PATH yet. On macOS or Linux, run export PATH="$PATH:$(go env GOPATH)/bin" and try again. That fixes it for this terminal; Appendix A shows how to make it permanent and what to do on Windows.

go install downloads code from the internet, so this is also a good moment to remember the “What not to give the AI” rule’s twin: only install tools you trust. This one comes from the Go team.

Write the check command

Make a check folder in tracker:

mkdir check

Create check/main.go and type it:

// Command check runs every Review check on the project.
package main

import (
    "fmt"
    "os"
    "os/exec"
    "strings"
)

func main() {
    if err := check(); err != nil {
        fmt.Fprintln(os.Stderr, "Check failed:", err)
        os.Exit(1)
    }
    fmt.Println("All checks passed.")
}

func check() error {
    out, err := run("gofmt", "-l", ".")
    if err != nil {
        return err
    }
    if out != "" {
        return fmt.Errorf("gofmt: these files need formatting")
    }
    for _, args := range [][]string{
        {"go", "vet", "./..."},
        {"go", "test", "./..."},
        {"govulncheck", "./..."},
    } {
        if _, err := run(args[0], args[1:]...); err != nil {
            return err
        }
    }
    return nil
}

// run prints a command, runs it and shows its output.
func run(name string, args ...string) (string, error) {
    fmt.Println("==>", name, strings.Join(args, " "))
    out, err := exec.Command(name, args...).CombinedOutput()
    fmt.Print(string(out))
    if err != nil {
        return "", fmt.Errorf("%s: %w", name, err)
    }
    return string(out), nil
}

It’s a second package main in your module, in its own folder, so it’s a separate program. os/exec runs other programs, the way you’d type them in a terminal, and CombinedOutput collects what they print. gofmt -l needs special handling: it succeeds even when it lists files, so check treats any output as a failure. The other three fail on their own when something’s wrong.

Why a Go program and not a shell script? Because it runs the same on Windows, macOS and Linux, and it uses nothing but the standard library.

Run it:

go run ./check
==> gofmt -l .
==> go vet ./...
==> go test ./...
ok      tracker 0.002s
?       tracker/check   [no test files]
ok      tracker/ledger  0.004s
ok      tracker/money   0.001s
==> govulncheck ./...
No vulnerabilities found.
All checks passed.

? tracker/check [no test files] is fine: check is a tool, not part of Tracker. As before, some lines may say (cached) instead of a time. govulncheck needs an internet connection to fetch the latest vulnerability data, so offline, check fails at its last step.

If govulncheck reports a vulnerability, read which package it names. When it’s in Go’s own standard library, the fix is usually to install the latest patch release of Go, such as 1.27.5 instead of 1.27.4, and run go run ./check again.

From now on, Review starts with go run ./check.

Specify

Add these sentences to SPEC.md:

10. `go run . serve` starts a web API on http://localhost:8080,
    using expenses.json.
11. POST /expenses with {"category":"Food","cents":350} adds and
    saves the expense, answers 201 Created, and returns the expense
    as JSON.
12. A body that isn't valid JSON, or an amount of zero or less,
    answers 400 Bad Request, and nothing is added.
13. GET /totals answers 200 OK with each category's total in cents,
    as JSON, like {"Food":449,"Transport":1200}.
14. Other methods on these paths answer 405 Method Not Allowed.

The API goes in a new package, api. Make the folder:

mkdir api

Create api/api_test.go:

package api

import (
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"

    "tracker/ledger"
)

// newTestHandler returns the API for a Tracker that uses store.
func newTestHandler(t *testing.T, store ledger.Storage) http.Handler {
    t.Helper()
    tr, err := ledger.Open(store)
    if err != nil {
        t.Fatalf("Open() error = %v", err)
    }
    return NewHandler(tr)
}

// send makes one request to h and returns the recorded response.
func send(h http.Handler, method, target, body string) *httptest.ResponseRecorder {
    req := httptest.NewRequest(method, target, strings.NewReader(body))
    rec := httptest.NewRecorder()
    h.ServeHTTP(rec, req)
    return rec
}

// add posts one expense and stops the test if it isn't created.
func add(t *testing.T, h http.Handler, body string) {
    t.Helper()
    rec := send(h, "POST", "/expenses", body)
    if rec.Code != http.StatusCreated {
        t.Fatalf("POST /expenses %s: status = %d, want %d", body, rec.Code, http.StatusCreated)
    }
}

func TestAddExpense(t *testing.T) {
    tests := []struct {
        name     string
        body     string
        wantCode int
    }{
        {"valid", `{"category":"Food","cents":350}`, http.StatusCreated},
        {"zero cents", `{"category":"Food","cents":0}`, http.StatusBadRequest},
        {"negative cents", `{"category":"Food","cents":-100}`, http.StatusBadRequest},
        {"not JSON", `coffee`, http.StatusBadRequest},
        {"cents as text", `{"category":"Food","cents":"350"}`, http.StatusBadRequest},
    }
    for _, tt := range tests {
        h := newTestHandler(t, &ledger.MemoryStorage{})
        rec := send(h, "POST", "/expenses", tt.body)
        if rec.Code != tt.wantCode {
            t.Errorf("%s: status = %d, want %d", tt.name, rec.Code, tt.wantCode)
        }
    }
}

func TestAddExpenseResponse(t *testing.T) {
    h := newTestHandler(t, &ledger.MemoryStorage{})
    rec := send(h, "POST", "/expenses", `{"category":"Food","cents":350}`)
    if got := rec.Header().Get("Content-Type"); got != "application/json" {
        t.Errorf("Content-Type = %q, want %q", got, "application/json")
    }
    want := `{"category":"Food","cents":350}` + "\n"
    if got := rec.Body.String(); got != want {
        t.Errorf("body = %q, want %q", got, want)
    }
}

func TestAddExpenseSaves(t *testing.T) {
    store := &ledger.MemoryStorage{}
    h := newTestHandler(t, store)
    add(t, h, `{"category":"Food","cents":350}`)

    tr, err := ledger.Open(store)
    if err != nil {
        t.Fatalf("Open() error = %v", err)
    }
    if got := tr.Totals()["Food"]; got != 350 {
        t.Errorf("saved Food total = %d, want 350", got)
    }
}

func TestTotals(t *testing.T) {
    h := newTestHandler(t, &ledger.MemoryStorage{})
    add(t, h, `{"category":"Food","cents":350}`)
    add(t, h, `{"category":"Transport","cents":1200}`)
    add(t, h, `{"category":"Food","cents":99}`)

    rec := send(h, "GET", "/totals", "")
    if rec.Code != http.StatusOK {
        t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
    }
    want := `{"Food":449,"Transport":1200}` + "\n"
    if got := rec.Body.String(); got != want {
        t.Errorf("body = %q, want %q", got, want)
    }
}

func TestWrongMethod(t *testing.T) {
    h := newTestHandler(t, &ledger.MemoryStorage{})
    rec := send(h, "DELETE", "/totals", "")
    if rec.Code != http.StatusMethodNotAllowed {
        t.Errorf("status = %d, want %d", rec.Code, http.StatusMethodNotAllowed)
    }
}

Each test maps to a sentence in your spec. A few details:

Run the tests:

go test ./...
ok      tracker (cached)
# tracker/api [tracker/api.test]
api/api_test.go:19:9: undefined: NewHandler
FAIL    tracker/api [build failed]
?       tracker/check   [no test files]
ok      tracker/ledger  (cached)
ok      tracker/money   (cached)
FAIL

One missing function. That’s the AI’s job.

Commit your tests and the check command first, so the AI’s changes stand on their own:

git add .
git commit -m "Add API tests and a check command" -m "Learned: httptest lets me test HTTP handlers without starting a server."

Use the AI: implementer

Ask:

Create package api in api/api.go with
func NewHandler(tr *ledger.Tracker) http.Handler, so that
go test ./... passes. Use http.ServeMux with method patterns like
"GET /totals". Also add a "serve" command to run in main.go that
starts the API on localhost:8080 with the same file storage.
Use only the standard library. Don't change any test files.

The prompt names the tools (http.ServeMux with method patterns) because the AI might otherwise reach for a third-party router. It also repeats the rule about tests. If you added “Never edit files ending in _test.go” to AGENTS.md in Chapter 5’s Practice, the AI has heard it twice.

Review the AI’s work

1. Check the scope

git status --short
 M main.go
?? api/api.go

M means modified; ?? means a new file Git hasn’t seen before. Two files: the new api.go and a change to main.go. No test files. If you see api/api_test.go here, the AI changed your tests: git restore api/api_test.go and ask again.

2. Let Go check

go run ./check

Every step should pass, ending with All checks passed. If go test fails, don’t fix the AI’s code yourself yet. Show it the failure and ask it to fix its own code without touching the tests.

3. Read the diff

A diff shows exactly what changed. New files don’t show up in git diff until Git knows about them, so first add everything, then look at what’s added:

git add .
git diff --staged --stat
 api/api.go | 45 +++++++++++++++++++++++++++++++++++++++++++++
 main.go    |  9 ++++++++-
 2 files changed, 53 insertions(+), 1 deletion(-)

--stat is the summary: which files changed, and how many lines were added (+) and removed (-). Your numbers will match only if the AI wrote exactly the book’s version; they’re a quick sense of size. Now the full change to main.go:

git diff --staged main.go

Here’s the diff for the book’s version:

diff --git a/main.go b/main.go
index fbf9662..5c1c268 100644
--- a/main.go
+++ b/main.go
@@ -3,10 +3,12 @@ package main
 import (
    "errors"
    "fmt"
+   "net/http"
    "os"
    "slices"
    "strconv"
 
+   "tracker/api"
    "tracker/ledger"
    "tracker/money"
 )
@@ -38,6 +40,11 @@ func run(args []string) error {
        return nil
    }
 
+   if len(args) == 1 && args[0] == "serve" {
+       fmt.Println("Listening on http://localhost:8080")
+       return http.ListenAndServe("localhost:8080", api.NewHandler(tracker))
+   }
+
    if len(args) == 3 && args[0] == "add" {
        category := args[1]
        cents, err := strconv.Atoi(args[2])
@@ -54,7 +61,7 @@ func run(args []string) error {
        return nil
    }
 
-   return errors.New("usage: go run . [add CATEGORY CENTS]")
+   return errors.New("usage: go run . [add CATEGORY CENTS | serve]")
 }
 
 func welcome() string {

How to read it:

The last hunk is the kind of change that’s easy to miss: the AI also updated the usage message. That’s good, but it’s also something you didn’t ask for. Reading diffs is how you notice every change, the ones you asked for and the ones you didn’t.

Now read api.go. For a new file, every line is +, so it’s easier to open it in your editor. Here’s the book’s version; the AI’s may differ:

// Package api serves a Tracker over HTTP, as JSON.
package api

import (
    "encoding/json"
    "log"
    "net/http"

    "tracker/ledger"
)

// NewHandler returns an http.Handler for the Tracker's API.
func NewHandler(tr *ledger.Tracker) http.Handler {
    mux := http.NewServeMux()
    mux.HandleFunc("POST /expenses", func(w http.ResponseWriter, r *http.Request) {
        var e ledger.Expense
        if err := json.NewDecoder(r.Body).Decode(&e); err != nil {
            http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest)
            return
        }
        if err := tr.Add(e.Category, e.Cents); err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }
        if err := tr.Save(); err != nil {
            log.Printf("save: %v", err)
            http.Error(w, "could not save the expense", http.StatusInternalServerError)
            return
        }
        writeJSON(w, http.StatusCreated, e)
    })
    mux.HandleFunc("GET /totals", func(w http.ResponseWriter, r *http.Request) {
        writeJSON(w, http.StatusOK, tr.Totals())
    })
    return mux
}

// writeJSON sends v as JSON with the given status code.
func writeJSON(w http.ResponseWriter, status int, v any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    if err := json.NewEncoder(w).Encode(v); err != nil {
        log.Printf("write JSON: %v", err)
    }
}

Ask the questions from earlier chapters, plus two for handlers:

  1. Do I understand it? Each HandleFunc takes a pattern and a function. That function is written right there, without a name, which is called a function literal. If that’s new, ask the AI to explain it.
  2. Does it fit this project? Standard library only, money in cents, every error checked.
  3. Does every error path return? After http.Error, the handler must stop. Otherwise it carries on and tries to write a second response.
  4. Does it use the right status codes? Compare each one with SPEC.md.

Notice what writeJSON does with an error it can’t send back. Once the status code is written, it’s too late to change it, so it logs the error instead of ignoring it.

Here are example suggestions you might make, or the AI might make if you ask it to review its own work (not real AI output):

Suggestion Keep? Why
Use a third-party router like chi or gorilla/mux Reject Since Go 1.22, http.ServeMux handles methods and path patterns. Standard library only.
Limit the request body size with http.MaxBytesReader Your call A real protection against huge requests. Keep it if you can explain it, and add a test.
Return errors as JSON, like {"error":"..."} Your call Nicer for programs that use the API. It changes the spec, so update SPEC.md and the tests first.
Accept amounts like 3.50 as a float Reject Money is whole cents.

4. Try it for real

Start the server:

go run . serve
Listening on http://localhost:8080

It keeps running and waits for requests. Leave it there, and open a second terminal. You’ll use curl, a command-line tool for making HTTP requests that comes with macOS, Linux and Windows 10 and later. On Windows PowerShell, type curl.exe instead of curl, and use the JSON quoting tips in Appendix A.

Your expenses.json from earlier chapters is still there, so:

curl -s localhost:8080/totals
{"Food":449,"Fun":1500,"Transport":1200}

Add an expense:

curl -s -X POST localhost:8080/expenses -d '{"category":"Food","cents":250}'
{"category":"Food","cents":250}

And try a bad one:

curl -s -X POST localhost:8080/expenses -d '{"category":"Food","cents":0}'
add "Food": amount must be more than zero

-s hides curl’s progress meter, -X POST sets the method, and -d sends the body. Go back to the first terminal and press Ctrl+C to stop the server. You’ll see signal: interrupt; that’s just go run reporting that you stopped it. Then run go run .: the Food total now includes the 2.50 you added through the API.

Review

Break it on purpose

Break 1: forget to save. In api.go, delete the whole if err := tr.Save(); ... } block, and run go test ./api:

--- FAIL: TestAddExpenseSaves (0.00s)
    api_test.go:82: saved Food total = 0, want 350
FAIL
FAIL    tracker/api 0.003s
FAIL

Without that block, the API would answer 201 Created and lose the expense when the server stops. The response looks perfect; only your test knew to look in storage. Put the block back.

Break 2: messy formatting. In api.go, change mux := http.NewServeMux() to mux := http.NewServeMux() and run go run ./check:

==> gofmt -l .
api/api.go
Check failed: gofmt: these files need formatting
exit status 1

check stops at the first failing step and names the file. Run gofmt -w api/api.go to fix it.

Check it yourself

Be SURE you can explain it. The AI typed it, but it’s your project.

Explain

Say it in your own words

Let the AI quiz you

Ask me two questions about the handlers in api/api.go or my tests in
api/api_test.go. Wait for my answers before you tell me if I'm right.

Write a Learned: line in your commit

The Break steps changed files after you staged them, so stage again before committing:

git add .
git commit -m "Add an HTTP API and a serve command" -m "Learned: a diff shows every change the AI made, including the ones I didn't ask for."

Update AGENTS.md if something surprised you

Did the AI use a third-party router, skip a return, or change more than you asked? Add a rule, for example:

Use net/http's ServeMux with method patterns; no third-party routers.

Practice (optional)

Write the request tests for a new endpoint, GET /totals/{category}:

15. GET /totals/Food answers 200 OK with the Food total as JSON:
    {"category":"Food","cents":449}
16. GET /totals/Travel, a category with no expenses, answers
    404 Not Found.

Add the sentences to SPEC.md, then write the tests in api/api_test.go: use add to set up some expenses, send to make the request, and check the status code and, for the 200 case, the exact body. Run them and watch them fail, then commit.

That’s the whole exercise: tests that say exactly what “done” means. If you want to go further, ask the AI to implement it, then review its diff. Hint for your review: in a pattern like "GET /totals/{category}", the handler reads the category with r.PathValue("category").

What you’ve done

Tracker is now a web API. You specified it with request tests, the AI built it, and you reviewed its work in four steps: scope, checks, diff and a real request. You also turned Review into one command, go run ./check, which checks formatting, mistakes, tests and known security problems every time.

The Where AI gets Go wrong box ended with a warning: your API answers many requests at once, and Tracker isn’t ready for that. In Chapter 7, you’ll see the problem with Go’s race detector, then make Tracker safe for many requests at the same time.