Final project: Expense Tracker
This is the last project of the book. It is one program that keeps
track of what you spend. It runs as a web server with a page for people
and a JSON API for programs, and the same .exe is also a
command-line client that talks to that API. Nothing in it is new. It
uses the rules in a type from Chapter 30, files from Chapter 31,
subcommands and flags from Chapter 32, wrapped errors from Chapter 33,
tests from Chapter 34, dates from Chapter 35, a mutex from Chapter 38,
Ctrl+C from Chapter 39, forms and templates from Chapters 42 and 43,
saving from Chapter 44, and all of Part 10: the API from Chapter 45, the
client from Chapter 46, logging, settings and shipping from Chapter 47,
and the folder layout from Chapter 48.
What to build
One program, expenses, with six commands:
| Command | What it does |
|---|---|
expenses serve |
Starts the web server: the page and the JSON API. |
expenses add |
Adds an expense through the API. |
expenses list |
Lists the expenses through the API. |
expenses report |
Shows the totals through the API. |
expenses delete |
Deletes an expense through the API. |
expenses version |
Prints the version. |
The server has these routes:
| Route | What it does |
|---|---|
GET / |
The page: the expenses, the totals, and a form.
?month=2026-11 shows one month. |
POST /expenses |
Adds an expense from the form, and redirects to /. |
POST /expenses/{id}/delete |
Deletes an expense from its button, and redirects to
/. |
GET /api/expenses |
The expenses as JSON. ?month=2026-11 gives one
month. |
POST /api/expenses |
Adds an expense sent as JSON. Replies 201 with the new expense. |
GET /api/expenses/{id} |
One expense as JSON. |
DELETE /api/expenses/{id} |
Deletes an expense. Replies 204 with no body. |
GET /api/report |
The totals as JSON. ?month=2026-11 gives one
month. |
The rules:
- An expense has a date, a category, an optional note, and an amount.
- The date is a real day written like
2026-11-25. The category is not empty, has at most 30 characters, and is stored in lower case. The note has at most 100 characters. Spaces around all three are trimmed. - The amount is typed like
12,12.5or12.50, and is kept as whole cents (1250), so that adding never gives0.30000000000000004. It is more than 0 and at most1000000.00. - The server gives each expense an ID. An ID is never used twice, even after a restart.
- Expenses are saved to
expenses.json, and are still there after a restart. - A mistake in what the user sent gets status 400, an unknown ID gets
404, and a failed save gets 500. The API always replies to an error with
{"error": "..."}.
From a real run, with the server running in one terminal, here is the other terminal:
.\expenses.exe add -date 2026-11-03 -category food -note lunch 12.50
Added expense 1: 2026-11-03 food 12.50 lunch
.\expenses.exe add -date 2026-11-04 -category transport 5
Added expense 2: 2026-11-04 transport 5.00
.\expenses.exe add -date 2026-10-30 -category Food 8
Added expense 3: 2026-10-30 food 8.00
.\expenses.exe add -date 2026-11-10 -category rent -note "November rent" 500
Added expense 4: 2026-11-10 rent 500.00 November rent
list shows them by date, oldest first:
.\expenses.exe list
ID DATE CATEGORY AMOUNT NOTE
3 2026-10-30 food 8.00
1 2026-11-03 food 12.50 lunch
2 2026-11-04 transport 5.00
4 2026-11-10 rent 500.00 November rent
report adds them up. Categories come largest first, and
months oldest first:
.\expenses.exe report
4 expenses in total
By category
rent 500.00
food 20.50
transport 5.00
By month
2026-10 8.00
2026-11 517.50
Total 525.50
With -month, both list and
report look at one month only:
.\expenses.exe report -month 2026-11
3 expenses in 2026-11
By category
rent 500.00
food 12.50
transport 5.00
By month
2026-11 517.50
Total 517.50
Deleting, and the errors. Each error goes to stderr, starts with
expenses:, and ends the program with exit code 1:
.\expenses.exe delete 2
Deleted expense 2.
.\expenses.exe delete 2
expenses: delete expense 2: the server replied 404: no expense has the id 2
.\expenses.exe add -category food lots
expenses: the amount "lots" must be a number like 12.50
.\expenses.exe list -month november
expenses: list expenses: the server replied 400: the month "november" must be written like 2026-11
The same data from the API, with curl.exe:
curl.exe http://localhost:8080/api/expenses/1
{
"id": 1,
"date": "2026-11-03",
"category": "food",
"note": "lunch",
"cents": 1250
}
curl.exe -i http://localhost:8080/api/expenses/99
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": "no expense has the id 99"
}
curl.exe -i also prints the headers Date
and Content-Length, which are left out here. Open
http://localhost:8080 in a browser to see the same expenses
as a page, with a form to add one, a Delete button on
each row, and the version at the bottom.
File layout
The project is a module called expenses, laid out as in
Chapter 48. Both versions are under
projects/09-expense-tracker/, with the same files:
starter/
go.mod
cmd/
expenses/
main.go
main_test.go
commands.go
client.go
serve.go
internal/
expense/
expense.go
expense_test.go
store/
store.go
store_test.go
web/
web.go
api.go
pages.go
web_test.go
templates/
home.html
finished/
(the same files)
cmd/expenses is the program, package main.
The three packages under internal/ can only be imported by
code in this module, which is what Chapter 48 uses internal
for.
To work on the starter, go into its folder. The program is in
./cmd/expenses, so that is what go run gets.
go test ./... runs the tests of every package in the
module:
cd projects/09-expense-tracker/starter
go run ./cmd/expenses serve
go test ./...
To run the finished version and its tests:
cd projects/09-expense-tracker/finished
go test ./...
go run ./cmd/expenses serve
To go back up to go-work afterwards:
cd ../../..
The finished tests pass. The times will be different for you:
ok expenses/cmd/expenses 0.041s
ok expenses/internal/expense 0.003s
ok expenses/internal/store 0.009s
ok expenses/internal/web 0.014s
The starter runs as it is. go run ./cmd/expenses serve
starts the server, and the page shows No expenses yet.
Sending the form gets status 400, with the line
TODO: ParseAmount is not written yet on the page. From a
second terminal, go run ./cmd/expenses list prints
No expenses., and add stops with
expenses: TODO: ParseAmount is not written yet.
The files that are finished in the starter: main.go,
serve.go, web.go, pages.go, the
template, and every test file. The TODOs are in the rest, each with a
comment that says what to do. In the starter most tests fail, and each
failure points at a function that is not written yet. Your job is to
make go test ./... say ok four times.
What to build it from
Each package has one job, and knows nothing about the jobs of the others:
| Package | Its job | Knows about |
|---|---|---|
internal/expense |
The rules: a valid expense, amounts, totals. | Nothing else. |
internal/store |
Keeping expenses in a JSON file, safely from many requests. | expense |
internal/web |
The page and the JSON API. | expense, and a store through an interface |
cmd/expenses |
The commands, the flags, the client, starting the server. | All of them |
The arrows only go one way. expense could be used by a
phone app, and store by a program with no web at all.
The rules:
internal/expense
An expense is a struct with JSON tags, as in Chapter 45:
type Expense struct {
ID int `json:"id,omitempty"`
Date string `json:"date"`
Category string `json:"category"`
Note string `json:"note"`
Cents int64 `json:"cents"`
}The date stays a string. A date like 2026-11-03 sorts
correctly as text, and its first seven characters are its month, which
is all the program needs.
In the starter, FormatCents, CheckMonth,
allDigits and the three sorting helpers are written. The
TODOs:
New(date, category, note, cents)trims and checks the values, and returns anExpensewith no ID, or an error that says what is wrong. Both the server and theaddcommand call it.ParseAmount(text)turns"12.5"into1250. It refuses"","-3","12.",".5","1,50"and"1.234".InMonth(list, month)keeps the expenses of one month, or all of them for"".Summarize(list)returns aReportwith the count, the total, and the totals per category and per month, sorted.
Run go test ./internal/expense until it says
ok.
The file:
internal/store
File is the guestbook's store from Part 9, grown a
little. It keeps next_id in the file next to the expenses,
which is how an ID is never used twice. Open,
List and save are written. The TODOs are
Get, Add and Delete. Each one
locks the mutex first, as List does. Add and
Delete build the new data, save it, and keep it only if
saving worked, as in Chapter 44. An unknown ID returns
ErrNotFound, a sentinel error as in Chapter 33.
Run go test ./internal/store.
The web: internal/web
web does not import store's type. It says
what it needs from a store with an interface:
type Store interface {
List() []expense.Expense
Get(id int) (expense.Expense, error)
Add(e expense.Expense) (expense.Expense, error)
Delete(id int) error
}*store.File has these four methods, so
serve.go can pass one in. The tests in
web_test.go pass a memoryStore instead, a
slice with the same four methods, so they need no file. There are no
package-level variables: New gets the store, the logger and
the version, and keeps them in an App. Its
Handler method returns every route:
// Pages for people.
mux.HandleFunc("GET /{$}", a.handleHome)
mux.HandleFunc("POST /expenses", a.handleAddForm)
mux.HandleFunc("POST /expenses/{id}/delete", a.handleDeleteForm)
// The JSON API for programs.
mux.HandleFunc("GET /api/expenses", a.handleList)
mux.HandleFunc("POST /api/expenses", a.handleCreate)
mux.HandleFunc("GET /api/expenses/{id}", a.handleGet)
mux.HandleFunc("DELETE /api/expenses/{id}", a.handleDelete)
mux.HandleFunc("GET /api/report", a.handleReport)
return a.logRequests(mux)web.go has the helpers from Chapter 45:
writeJSON, writeError, readJSON
(one JSON object, no unknown fields, at most 4096 bytes) and
readID. The template is embedded, as in Chapter 47, so the
.exe needs no other files. pages.go, the page
side, is finished. In api.go, handleList and
handleGet are written. The TODOs are
handleCreate, handleDelete and
handleReport.
Run go test ./internal/web.
The program:
cmd/expenses
main sets up Ctrl+C, as in Chapter 39, and calls
run. run picks the command, and returns every
error instead of printing it, so main is the one place that
prints an error and exits:
func run(ctx context.Context, args []string, out io.Writer) error {
if len(args) == 0 {
return fmt.Errorf("no command given\n%s", usage)
}
command := args[0]
rest := args[1:]
switch command {
case "serve":
return runServe(ctx, rest)
case "add":
return runAdd(ctx, rest, out)
case "list":
return runList(ctx, rest, out)
case "report":
return runReport(ctx, rest, out)
case "delete":
return runDelete(ctx, rest, out)
case "version":
fmt.Fprintln(out, "expenses", version)
return nil
case "help", "-h", "-help", "--help":
fmt.Fprintln(out, usage)
return nil
default:
return fmt.Errorf("unknown command %q\n%s", command, usage)
}
}Because run takes its arguments and an
io.Writer, main_test.go can call it like a
user would, against a real server started with
httptest.NewServer, and read what it printed.
Each command has its own flag.FlagSet, as in Chapter 32,
so list has -month and add has
-category. serve.go is the server from Chapter
47: slog, flags with environment variables as their
defaults, time limits, and a clean stop on Ctrl+C. It is finished.
client.go is the client from Chapter 46, with
do and List written. The TODOs are
Add, Delete and Report in
client.go, and runReport and
runDelete in commands.go. runAdd
and runList are finished, so copy their shape.
Run go test ./... once more. When all four lines say
ok, the program is done.
Hints
- Work from the inside out:
expense, thenstore, thenweb, thencmd/expenses. Each package has its own tests, and each one only needs the packages before it. go test -run TestParseAmount ./internal/expenseruns one test. Add-vto see each case.- Amounts never pass through
float64.ParseAmountworks on the text, andFormatCentsuses/ 100and% 100on whole numbers. Chapter 13 shows why0.1 + 0.2is not0.3. time.Parse(DateLayout, "2026-11-31")is an error, because November has 30 days. That one line checks the whole date.- Sort with
slices.SortFuncand a named function, as in Chapter 28. A map has no order, so without sorting, the report would come out in a different order on each run, and the tests would fail now and then. InMonthandtoSumsstart from an empty slice,[]Expense{}, notnil. Encoded to JSON, an empty slice is[]and a nil slice isnull, and a client should not have to handle both.- In
handleCreate, find the too-large body witherrors.As, as in Chapter 45. It is the only error fromreadJSONthat is not the client's bad JSON. - The client checks an expense with
expense.Newbefore it sends it, so a typing mistake gets a quick answer even with no server. The server checks again, because any program can call the API. Expensehasomitemptyon its ID. A new expense has ID 0, so the client sends noidfield, and the server's strict decoding does not refuse it.
Ship it
Build the program with a version number, as in Chapter 47. From the
finished folder (or your starter, once it passes):
go build -ldflags "-X main.version=1.0.0" -o expenses.exe ./cmd/expenses
.\expenses.exe version
expenses 1.0.0
Without -ldflags, the version is dev, which
is what go run shows. The template is inside the
.exe, so expenses.exe is the only file anyone
needs. Copy it to an empty folder, for example
C:\Users\you\expenses, and start the server there:
.\expenses.exe serve
time=2026-11-25T09:30:12.418+07:00 level=INFO msg="server starting" addr=localhost:8080 file=expenses.json expenses=0 version=1.0.0
The time and the zone will be yours. expenses.json
appears in that folder the first time an expense is saved. Leave this
terminal open, open a second one in the same folder, and use the
client:
.\expenses.exe add -category food -note coffee 3.20
Added expense 1: 2026-11-25 food 3.20 coffee
With no -date, add uses today's date. The
server's terminal logs each change:
time=2026-11-25T09:31:40.102+07:00 level=INFO msg="expense added" id=1 category=food cents=320
Press Ctrl+C in the server's terminal. It finishes the requests that are running, and stops:
time=2026-11-25T09:35:03.771+07:00 level=INFO msg="shutting down"
time=2026-11-25T09:35:03.772+07:00 level=INFO msg="server stopped"
Now run .\expenses.exe list again. With nothing
listening, the client says so:
expenses: list expenses: could not reach the server (is "expenses serve" running?): Get "http://localhost:8080/api/expenses": dial tcp [::1]:8080: connectex: No connection could be made because the target machine actively refused it.
The end of that line comes from Windows, and can be worded differently on your computer.
The settings come from flags, or else from environment variables, or
else from the defaults. .\expenses.exe serve -h lists them.
To use another port and a JSON log for one PowerShell window:
$env:EXPENSES_ADDR = "localhost:9090"
.\expenses.exe serve -log-format json -log-level debug
The client reads EXPENSES_ADDR too, so in a window where
it is set, add, list and report
find the server on port 9090 with no -addr. With
-log-level debug, the server also logs one line for every
request, with its status and how long it took.
A bigger challenge (optional)
- Edit. Add
PUT /api/expenses/{id}, anUpdatemethod on the store, and anexpenses editcommand. Write the tests first. - A budget. Let
reporttake-budget 400, and print how much is left this month, or how much too much was spent. - CSV. Add
expenses export -month 2026-11, which prints the month as CSV withencoding/csv, ready to open in a spreadsheet. - Search. Add
?category=foodtoGET /api/expenses, and a-categoryflag tolist. - The page. Add a link on each category in the totals that shows only that category, and keep the chosen month when the form is sent.
None of these are required to finish the project.
Done?
When go test ./... says ok four times,
expenses.exe version prints the version you built with, and
expenses added from the second terminal show up on the page and survive
a restart of the server, the Expense Tracker is done. So is the
book.
Where to go next
Look back at what you can do now. You can plan a program on paper,
split it into packages with one job each, check its input, keep its data
in a file, test it, make it do several things at the same time, put it
on the web with a page and an API, call other APIs, and hand it to
someone as one .exe. That is enough to build most small
tools that people actually use.
The best next step is a program of your own. Pick something you or someone near you would use every week: a reading log, a tool that tidies a folder of photos, a scoreboard for a club, a small API for a phone app. Plan it on paper as in Part 1, start with the rules and their tests, and add the web or the command line last. You will get stuck, and the error messages and the chapters here will get you unstuck.
When you want to read more:
- A Tour of Go and Effective Go go over the language again, faster, with the points this book left out, such as generics.
- The standard library
documentation is where every package in this book is described in
full. Reading the page of a package you already use, such as
stringsornet/http, always turns up something useful. - Go by Example has a short, runnable example for almost every task.
- Databases are the usual next step after JSON files.
database/sqlwith SQLite or PostgreSQL needs a driver, your first package from outside the standard library, but keeps the same shape as this project: replaceinternal/store, and keep theStoreinterface.
Thank you for reading, and happy building.