Skip to content
Tutorials Center
My learning

Topics

Lesson 133 of 147 ยท Projects

Project: Command-Line To-Do Manager

Build a to-do manager in Go in four stages - a task store and command loop, flag parsing with FlagSet, JSON persistence to a file, and table-driven tests you can run.

A to-do manager is the classic first Go project because it touches everything a real command-line tool needs: a data model, a place to keep it, a way to read commands, error handling that helps the user, and files that survive between runs. It is small enough to finish in one sitting, yet the structure you build here (a store, a command layer and a thin main) is the same one that larger tools use.

You will build it in four stages, and each stage is a complete program you can run and change. In stage 1 you create a Task type, a slice-backed store and a loop that reads commands from the Input box. In stage 2 you parse options such as -p high with the standard library's flag package. In stage 3 you save the tasks as JSON in a temporary file and load them in a second "session". In stage 4 you restructure the code so that it can be tested, and you run real table-driven tests. Along the way you will use structs, slices, custom errors, JSON and files.

Our editor runs programs without a terminal, so commands arrive through the Input box (the program reads standard input) instead of command-line arguments. In a real tool you would call os.Args[1:] and the logic would be exactly the same. The Input box is pre-filled with a sample session, and you can edit it and press Run again.

The plan

Stage What you build Main Go ideas
1 A Task type, a store, and a command loop Structs, slices, bufio.Scanner, sentinel errors
2 Options like add -p high -due 2026-12-24 Buy gifts flag.FlagSet, flag.Value, iota enums, time.Parse
3 Tasks saved to disk and loaded in a second session encoding/json, os.CreateTemp, atomic writes, errors.Is
4 Testable design and a test suite io.Writer injection, table-driven tests, testing.Main

Everything in stages 1 and 2 lives in memory. The commands the finished tool understands are:

TEXT
add [-p low|normal|high] [-due YYYY-MM-DD] <title...>
list [-all] [-p low|normal|high]
done <id>
rm <id>
help
quit

Stage 1: a store and a command loop

Start with the data. A Task has an id, a title and a done flag. The Store owns a slice of tasks and the next id to hand out, and its methods are the only code that touches the slice. Methods return errors instead of printing, so the same store could serve a command line, a web page or a test.

Two small design decisions are worth noticing. First, ids are never reused: nextID only grows, so #3 always means the same task even after #2 is removed. Second, there is one exported sentinel error, ErrNotFound, which callers can recognize with errors.Is.

The command loop reads a line, splits off the first word with strings.Cut, and uses a switch to pick the command. A bad command or a failing method prints a message and the loop goes on, because a to-do tool should not crash on a typo.

Go Stage 1: tasks in memory and a command loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Read the output from the top: three added lines, a first list with three open tasks, then done 2 and rm 3, a second list that shows [x] 2 and no task 3, and finally two errors, one for done 9 (task 9: task not found) and one for the unknown command dance. The program stops at quit, so the last line of the input is never read.

A few details deserve attention:

  • fmt.Errorf("task %d: %w", id, ErrNotFound) adds context while keeping the original error inside. A caller can print the full message or ask errors.Is(err, ErrNotFound). See wrapping errors.
  • slices.Delete(s.tasks, i, i+1) removes one element and keeps the order. It shifts the tail left, so any slice you obtained from s.tasks earlier would see changed data. List therefore returns slices.Clone(s.tasks), a copy that callers can keep or sort freely.
  • bufio.Scanner reads one line at a time and handles the end of input for you: Scan returns false at EOF, so main ends without special code. See reading input.
  • The switch assigns to a variable err declared before it, so there is one place at the bottom that reports problems. Handling errors in one spot keeps the command branches short.

Stage 2: options with the flag package

Real to-do tools let you say how important a task is and when it is due. You could parse -p high by hand, but the standard library already does it, including error messages and defaults. The flag package normally works on the program's own arguments, but flag.NewFlagSet creates an independent set of flags that can parse any list of strings. That is exactly what you want when every command (add, list) has different options.

Three details make this stage interesting.

  1. A priority type with iota. Priority is an int with three named values. Writing Low Priority = iota - 1 makes Low equal to -1, Normal equal to 0 and High equal to 1. The zero value is Normal, so a Task{} is automatically a normal-priority task, and sorting by the number puts high priority first. See constants and iota.
  2. A custom flag type. Any type with String() string and Set(string) error methods implements flag.Value, so fs.Var(&priority, "p", "...") parses -p high straight into a Priority and rejects -p urgent with a clear message.
  3. Dates without the clock. Due dates are parsed with time.Parse("2006-01-02", text). The program never calls time.Now(); instead the app has a today field, so the "overdue" label depends only on the input. That makes the output repeatable here and, later, testable.

Flags must come before the positional arguments, as with most Go tools: add -p high Buy gifts works, but add Buy gifts -p high treats -p as part of the title.

Go Stage 2: priorities, due dates and FlagSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Compare the output with the input line by line. The tasks print in a table (text/tabwriter pads the columns for you), sorted so open tasks come first and, within them, high priority before normal before low. The first list shows Task 3 with (overdue) because its due date is before the app's fixed "today" of 2026-11-01. The error lines show what the packages report on their own: -p urgent fails with the text from our Set method, wrapped by the flag package as invalid value "urgent" for flag -p: ..., -due 31/12/2026 fails in time.Parse (we replace its message with a friendlier one), and a lone -p reports flag needs an argument: -p. After done 2, the plain list hides the finished task, list -all -p high shows only the high-priority one, and list -all finally shows the finished task at the bottom.

Some things to notice in the code:

  • fs.SetOutput(io.Discard) stops the flag package from printing its own error and usage text. Without it, each mistake would be reported twice, once by flag and once by our error: line. Whenever you build a user-facing tool on FlagSet, decide who owns the message.
  • fs.Visit calls a function for each flag that was set on the command line. That is how list tells "no -p given" from "-p normal given", since Normal is also the zero value.
  • cmp.Or(a, b) returns the first non-zero value. In a comparison function it chains sort keys: finished-ness first, then priority descending. SortStableFunc keeps equal tasks in id order.
  • App.out is an io.Writer. main passes os.Stdout; stage 4 will pass a buffer.

If a command-line tool grows many subcommands, look at third-party libraries such as Cobra. For a tool with a handful of commands, FlagSet per command is simple and has no dependencies. See flag and command-line tools.

Stage 3: saving to a JSON file

A to-do list that forgets everything on exit is a demo. Stage 3 stores the tasks in a JSON file. The Store gets Load and Save, and Task gets struct tags, so the file has readable lowercase keys. Two types need to convert themselves: Priority implements MarshalText and UnmarshalText, so the file says "high" instead of 1, and the zero time.Time is skipped with the omitzero tag option from Go 1.24.

Two decisions here prevent real-world data loss:

  • A missing file is not an error. Load checks errors.Is(err, fs.ErrNotExist) and returns an empty store, because the first run of the program has no file yet. Any other error (a corrupt file, a permissions problem) is returned, never ignored. Silently starting from an empty list and then saving it would overwrite the user's tasks.
  • Save writes a temporary file and renames it. If the program dies halfway through os.WriteFile, a plain write would leave a half-written file. A rename is atomic on the same file system, so readers see either the old file or the new one, never a mixture.

The program runs two "sessions" against the same file. Each session loads the file, executes the commands it is given, and saves. The second session proves that the first one's tasks survived. The file lives in a temporary directory that the program deletes at the end.

Go Stage 3: two sessions sharing a JSON file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Look at tasks.json in the output: the keys are lowercase, "priority": "high" is text, and the second task has no "due" key at all, because the zero date was omitted. Session 2 starts with no memory of session 1 except the file, and it continues numbering at #4, since next_id was saved too. In the last part the program writes broken JSON on purpose: Load reports a clear error that wraps the JSON syntax error with %w, and session returns before saving, so the damaged file is not overwritten by an empty list.

The save is atomic, but two programs running at the same time can still overwrite each other's changes: each loads the file, edits its own copy, and saves, so the last writer wins. A real tool that must handle this needs a lock file or a database. For a personal to-do list, the simple approach is fine.

Stage 4: make it testable

Stage 3 already has the shape that makes testing easy. App writes to an io.Writer and takes the clock as a field (today), and Store is a plain struct. A test needs no terminal, no real time and, with t.TempDir(), no cleanup code.

A good test suite for this tool checks three layers:

  1. The store: adding, completing and removing, including the not-found error.
  2. The command layer: strings in, text out, with a table of inputs and expected results.
  3. Persistence: a store saved and loaded again equals the original, and a missing file gives an empty store.

In your own project the tests live in todo_test.go next to the code, and go test finds them. Here is what that file looks like (read-only, because our editor cannot run go test):

Go
package main

import (
	"path/filepath"
	"strings"
	"testing"
)

func newTestApp(t *testing.T) (*App, *strings.Builder) {
	t.Helper()
	var out strings.Builder
	app := &App{store: &Store{NextID: 1}, out: &out}
	return app, &out
}

func TestExec(t *testing.T) {
	tests := []struct {
		name    string
		lines   []string
		want    string // the output of the LAST line
		wantErr string // part of the expected error, "" for none
	}{
		{"add shows id and priority", []string{"add -p high Buy gifts"}, "added #1: Buy gifts (high)\n", ""},
		{"empty title", []string{"add -p high"}, "", "needs a title"},
		{"bad priority", []string{"add -p urgent X"}, "", "not a priority"},
		{"unknown id", []string{"done 7"}, "", "task not found"},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			app, out := newTestApp(t)
			var err error
			for _, line := range tt.lines {
				out.Reset()
				err = app.Exec(line)
			}
			// check err against tt.wantErr and out.String() against tt.want ...
		})
	}
}

func TestSaveAndLoad(t *testing.T) {
	path := filepath.Join(t.TempDir(), "tasks.json")
	// save a store, load it back, compare ...
}

The runnable program below does the same job in a way the editor can execute. It contains the whole application from stage 3 (shortened here to what the tests need) and a main that starts the real testing machinery with testing.Main, the function go test itself uses. The test functions are written exactly as they would be in a _test.go file.

Go Stage 4: running real table-driven tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Every subtest passes, and the output lists them by name, such as TestExec/ids_are_not_reused. That one case guards a design decision from stage 1: removing the highest id must not let the next task reuse it. If you later change Add to use len(Tasks)+1 as the id, exactly that test fails, and its name tells you why.

Notice how little the tests needed: an App with a strings.Builder as its output, a temporary directory from t.TempDir() (removed automatically), and no clock, because today is a field. This is the practical payoff of the design: dependencies (output, time, file path) are passed in, not reached for. See table-driven tests for more on the technique.

In a real project, run the whole suite with go test ./... and add -race and -cover when you want them. The commands look like this on your machine:

Terminal
go test ./...
go test -run 'TestExec/ids' -v
go test -cover

Ideas for extending the tool

  • Add an edit <id> <new title> command and an undo that keeps the previous store in memory.
  • Support tags (#home, #work) and a list -tag work filter.
  • Read the file path from the TODO_FILE environment variable, falling back to a file in os.UserConfigDir().
  • Print colored output only when standard output is a terminal.
  • Use os.Args[1:] directly, so todo add -p high Buy gifts works in a real terminal. Only the main function changes.
  • Swap the JSON file for SQLite behind a Store interface, and keep the tests (see databases with database/sql).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the Priority enum, Low Priority = iota - 1 is followed by Normal and High. What are their values?

    iota is 0 on the first line, so Low is 0 - 1 = -1. The following lines repeat the expression with iota 1 and 2, giving 0 and 1. The zero value is therefore Normal.
  2. 2. Why does the program call fs.SetOutput(io.Discard) on each FlagSet?

    By default a FlagSet prints errors and usage to standard error. With ContinueOnError the error is also returned, so printing it twice would be noise.
  3. 3. Load returns an empty store when the file does not exist but returns an error when the JSON is invalid. Why?

    The first run has no file yet, so that case is expected. Treating corruption as 'empty' and saving would destroy the user's data.
  4. 4. What does Save gain by writing to path + ".tmp" and then calling os.Rename?

    A rename within one file system is atomic: readers see the complete old file or the complete new file. It does not protect against two writers overwriting each other's changes.
  5. 5. What does t.Run(tt.name, ...) inside a loop over a table give you?

    Each row becomes a subtest such as TestExec/empty_title, so failures name the case and you can run one row alone.

Summary

  • Keep data and logic apart from input and output. A Store with methods, an App that writes to an io.Writer, and a small main make every layer easy to test.
  • Return errors instead of printing them, wrap them with %w, and expose sentinel errors such as ErrNotFound for errors.Is.
  • flag.NewFlagSet parses any list of strings, so each subcommand can have its own options; implement flag.Value for custom types, and flags must come before positional arguments.
  • Use iota for enums and make the zero value a sensible default. MarshalText and UnmarshalText control how a type appears in JSON.
  • Treat a missing data file as normal and a corrupt one as an error. Save through a temporary file and os.Rename so a crash cannot leave half a file.
  • Pass the clock, the output and the file path into your code instead of reaching for globals. Then table-driven tests with t.Run, t.TempDir and a strings.Builder are short and fast.

Next: Project: Word Frequency Analyzer