Explain it simply
Explain it simply
So far the Task Manager keeps its tasks only in memory, so closing the program loses everything. In this part the tasks go into a tasks.json file and are read back the next time the program starts.
Think of a word processor's auto-save. While you type, it saves in the background every few minutes, and it saves one last time when you close it. In Go, that background helper is a goroutine and "every few minutes" is a time.Ticker. Because two goroutines touch the same task list, a mutex makes them take turns.
Problem → Why → Solution
The problem: auto-save exists, yet data is lost
A first quick attempt at auto-save often looks like this. A goroutine saves every 10 seconds while main keeps adding tasks. It seems to work when you try it, but two problems are hiding.
First, the whole program stops the moment main returns, so tasks added after the last tick never reach the disk. Second, two goroutines read and write m.tasks at the same time without a lock. That is a data race, and it can produce strange results in the JSON.
go func() {
for range time.Tick(10 * time.Second) {
m.Save("tasks.json") // reads m.tasks with no lock, error ignored
}
}()
m.Add("Write report") // writes m.tasks at the same time: data race
// main returns here: the goroutine dies, the last edits are never savedGo does not wait for goroutines
When main returns, the program ends; it never waits for goroutines that are still running. So you need both a way to tell the goroutine to stop (a done channel) and a way to wait until it really has (a sync.WaitGroup). The data race can be caught at runtime with go run -race, and the fix is to guard the shared state with a mutex.
Core concept: safe persistence and a goroutine you control
Part 3 breaks down into five pieces: the first two are about the file, the last three about concurrency.
1. Struct tags and JSON
A tag such as `json:"title"` sets the JSON key name. json.MarshalIndent turns a []Task into readable JSON bytes and json.Unmarshal does the reverse. Both see only exported fields, which is why Part 1 started the field names with capitals.
2. Load and Save carefully
A missing file just means the first run, not an error: detect it with errors.Is(err, fs.ErrNotExist) and start empty. Every other error, such as a permission problem or broken JSON, must be returned. After loading, recompute nextID from the highest ID. Save writes tasks.json.tmp first and then replaces the real file with os.Rename, so a crash mid-write leaves either the old file or the new one, never half of one.
3. A mutex guards the shared state
The auto-save goroutine and main share one TaskManager, so every method starts with m.mu.Lock() and releases it with defer m.mu.Unlock(). Only one goroutine at a time can touch tasks, nextID or dirty.
4. A dirty flag and a ticker
Add and Complete set dirty = true, and a successful Save sets it back to false. Each tick saves only when dirty is set, so an idle program does not rewrite the disk for nothing.
5. Stop with select, wait with a WaitGroup
AutoSave waits in a select on two channels: the tick channel and the done channel. When main calls close(done), the goroutine does one final save and returns. main waits for that return with wg.Wait(), so the last edits are guaranteed to be on disk before it continues.
Who touches what
----------------
main goroutine auto-save goroutine
-------------- -------------------
Add / Complete --lock--+ tick --> saveIfDirty --lock--+
| |
+--> TaskManager{tasks,nextID,dirty} <+
close(done) ----------------> final saveIfDirty, return
wg.Wait() <--------------- wg.Done()- Lock before touching shared state
- Write a temp file, then rename it
- Signal the stop with close(done)
- Wait for the goroutine: wg.Wait()
Every time you start a goroutine, answer two questions: who tells it to stop, and who waits for it?
General pattern
func (s *Store) Run(tick <-chan time.Time, done <-chan struct{}) {
for {
select {
case <-tick:
s.saveIfChanged()
case <-done:
s.saveIfChanged() // final save
return
}
}
}A background loop uses select to wait for a work signal (tick) and a stop signal (done). On done it finishes its cleanup and returns.
Part 3 code: save, load and auto-save
To keep the demo quick, the ticker fires every 20ms, and the file lives in a temporary folder made with os.MkdirTemp, which defer os.RemoveAll deletes at the end. Remove is unchanged from Part 2, so it is left out to keep the file shorter.
How many ticks fire depends on the machine, but the output is always the same, because the file is read only after the final save. At the end a fresh TaskManager loads the file, simulating the next program start.
package main
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
var (
ErrEmptyTitle = errors.New("title must not be empty")
ErrNotFound = errors.New("task not found")
)
// Remove and the rest of Part 2 work unchanged; they are left out here.
type TaskManager struct {
mu sync.Mutex // guards every field below
tasks []Task
nextID int
dirty bool // changed since the last successful save
}
func (m *TaskManager) Add(title string) (Task, error) {
title = strings.TrimSpace(title)
if title == "" {
return Task{}, ErrEmptyTitle
}
m.mu.Lock()
defer m.mu.Unlock()
m.nextID++
t := Task{ID: m.nextID, Title: title}
m.tasks = append(m.tasks, t)
m.dirty = true
return t, nil
}
func (m *TaskManager) Complete(id int) error {
m.mu.Lock()
defer m.mu.Unlock()
for i := range m.tasks {
if m.tasks[i].ID == id {
m.tasks[i].Done = true
m.dirty = true
return nil
}
}
return fmt.Errorf("complete task %d: %w", id, ErrNotFound)
}
func (m *TaskManager) List() {
m.mu.Lock()
defer m.mu.Unlock()
for _, t := range m.tasks {
status := "[ ]"
if t.Done {
status = "[x]"
}
fmt.Printf("%s %d. %s\n", status, t.ID, t.Title)
}
}
// Save writes a temp file and renames it over the real one, so a crash
// in the middle of a write can never leave a half-written tasks.json.
func (m *TaskManager) Save(path string) error {
m.mu.Lock()
defer m.mu.Unlock()
data, err := json.MarshalIndent(m.tasks, "", " ")
if err != nil {
return fmt.Errorf("encode tasks: %w", err)
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, data, 0o644); err != nil {
return fmt.Errorf("save: %w", err)
}
if err := os.Rename(tmp, path); err != nil {
return fmt.Errorf("save: %w", err)
}
m.dirty = false
return nil
}
// Load replaces the tasks with the file's content. A missing file is
// not an error: it simply means this is the first run.
func (m *TaskManager) Load(path string) error {
data, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("load: %w", err)
}
var tasks []Task
if err := json.Unmarshal(data, &tasks); err != nil {
return fmt.Errorf("load %s: %w", filepath.Base(path), err)
}
m.mu.Lock()
defer m.mu.Unlock()
m.tasks, m.nextID, m.dirty = tasks, 0, false
for _, t := range tasks {
m.nextID = max(m.nextID, t.ID)
}
return nil
}
// AutoSave saves after each tick if something changed, and one final
// time when done is closed, then returns.
func (m *TaskManager) AutoSave(path string, tick <-chan time.Time, done <-chan struct{}) {
for {
select {
case <-tick:
m.saveIfDirty(path)
case <-done:
m.saveIfDirty(path)
return
}
}
}
func (m *TaskManager) saveIfDirty(path string) {
m.mu.Lock()
dirty := m.dirty
m.mu.Unlock()
if dirty {
if err := m.Save(path); err != nil {
fmt.Fprintln(os.Stderr, "auto-save:", err)
}
}
}
func main() {
dir, err := os.MkdirTemp("", "taskmgr-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "tasks.json")
m := &TaskManager{}
if err := m.Load(path); err != nil {
fmt.Println(err)
return
}
fmt.Println("tasks on first run:", len(m.tasks))
ticker := time.NewTicker(20 * time.Millisecond)
defer ticker.Stop()
done := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
m.AutoSave(path, ticker.C, done)
}()
for _, title := range []string{"Write report", "Review pull request"} {
if _, err := m.Add(title); err != nil {
fmt.Println("add failed:", err)
}
}
if err := m.Complete(1); err != nil {
fmt.Println(err)
}
time.Sleep(50 * time.Millisecond) // keep working while ticks fire
close(done) // ask the auto-saver for a final save...
wg.Wait() // ...and wait until it has really finished
data, err := os.ReadFile(path)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("--- tasks.json ---\n%s\n", data)
next := &TaskManager{} // simulate the next program start
if err := next.Load(path); err != nil {
fmt.Println(err)
return
}
t, err := next.Add("Plan next sprint")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("after restart, the new task gets ID", t.ID)
next.List()
}Code breakdown
- First run is not an error
if errors.Is(err, fs.ErrNotExist) {os.ReadFile returns a *fs.PathError, but errors.Is finds the fs.ErrNotExist inside it. A missing file means start empty; every other error is returned.
- Recompute the counter
m.nextID = max(m.nextID, t.ID)After loading, nextID becomes the highest ID in the file, so the first task after a restart gets ID 3. The built-in max function is available from Go 1.21 onward.
- Atomic replace
if err := os.Rename(tmp, path); err != nil {The full JSON is written to the tmp file first, then the rename swaps it in as one step. If the rename fails, dirty stays true, so the next tick tries again.
- Two ways out of the loop
case <-done:Receiving from a closed channel succeeds immediately, so even while waiting for the next tick the goroutine notices the stop signal, does the final save and leaves.
- Signal, then wait
wg.Wait() // ...and wait until it has really finishedclose(done) only asks the goroutine to stop. wg.Wait() blocks until its final save is done and wg.Done() runs, so the os.ReadFile on the next lines reads the complete file.
tasks on first run: 0
--- tasks.json ---
[
{
"id": 1,
"title": "Write report",
"done": true
},
{
"id": 2,
"title": "Review pull request",
"done": false
}
]
after restart, the new task gets ID 3
[x] 1. Write report
[ ] 2. Review pull request
[ ] 3. Plan next sprintWhy AutoSave takes the tick channel as a parameter
AutoSave does not create its own ticker; it accepts a <-chan time.Time. Production code passes ticker.C, while a test can pass its own channel and send ticks by hand with tick <- time.Now(), without waiting real seconds. Moving a dependency into a parameter like this makes code much easier to test.
An empty list is saved as null
If m.tasks is a nil slice, json.MarshalIndent writes null instead of []. Go's Load reads null back as a nil slice, so this program is fine, but if other tools read the file, replace nil with []Task{} before saving.
In real projects
In real projects
Writing a temp file and renaming it is common in editors, package managers and any service that stores configuration on disk, because the file stays intact whenever power fails or the process is killed. Keep the temp file in the same folder as the final file; across folders a rename may not be atomic, or may fail outright.
Stopping a background goroutine with a done channel (or a context.Context) and waiting for it with a WaitGroup is the core of graceful shutdown. HTTP servers, queue consumers and metrics flushers all follow this shape. Real apps also keep their data file in a platform-appropriate place such as os.UserConfigDir() rather than the working directory.
Common mistakes
Common mistakes
Ignoring the Load error
With _ = m.Load(path), a file with broken JSON is treated as an empty list, and auto-save then writes that empty list to disk, destroying the user's old data for real. Accept only a missing file; stop on every other error.
Not waiting for the goroutine
If main returns right after close(done), the final save may or may not finish. Sending done <- true on an unbuffered channel only waits until the goroutine receives, not until its save completes. Always call wg.Wait() after close(done).
Sharing the slice without a mutex
If Add appends while Save is reading m.tasks, that is a data race, and under Go's memory model the result is unpredictable. Test with go run -race and take the lock in every method that touches a shared field.
Mini challenge
Keep a backup and recover from a broken file
Change Save so it keeps the previous file as tasks.json.bak before writing the new one. Then write LoadWithBackup, which falls back to the backup when the main file is broken. In the demo, save twice, cut the main file short as if a write was interrupted, and recover.
- If the file already exists, Save moves it to path+".bak" with os.Rename before writing
- Load puts only filepath.Base(path) in its error messages, never the full path
- LoadWithBackup returns the name of the file it actually loaded
- A missing file (first run) is not treated as an error
package main
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
)
// TODO: reuse the Task struct (with JSON tags) and a TaskManager
// with tasks and nextID, plus a simple Add(title string).
// Save keeps the previous file as path+".bak" before writing the new one.
func (m *TaskManager) Save(path string) error {
// TODO: marshal, rename an existing file to .bak, then write
}
func (m *TaskManager) Load(path string) error {
// TODO: read + unmarshal; wrap errors with filepath.Base(path)
}
// LoadWithBackup tries path first, then path+".bak".
func (m *TaskManager) LoadWithBackup(path string) (string, error) {
// TODO: treat fs.ErrNotExist as a first run; print a warning
// before falling back to the backup
}
func main() {
// TODO: MkdirTemp + defer RemoveAll; save one task, then two tasks
// TODO: overwrite tasks.json with []byte(`[{"id": 1, "title": "Wri`)
// TODO: LoadWithBackup into a new TaskManager and print the result
fmt.Println("start here")
}Expected: A warning, "warning: load tasks.json: unexpected end of JSON input", then "restored 1 task(s) from tasks.json.bak" and "1. Write report". The backup is the version from before the second save, so it holds one task.
Show hint
If os.Stat(path) returns no error, the file exists. Use %w in Load's fmt.Errorf so errors.Is(err, fs.ErrNotExist) still works after wrapping.
Show solution
package main
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
)
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
type TaskManager struct {
tasks []Task
nextID int
}
func (m *TaskManager) Add(title string) {
m.nextID++
m.tasks = append(m.tasks, Task{ID: m.nextID, Title: title})
}
// Save keeps the previous file as path+".bak" before writing the new one.
func (m *TaskManager) Save(path string) error {
data, err := json.MarshalIndent(m.tasks, "", " ")
if err != nil {
return err
}
if _, err := os.Stat(path); err == nil {
if err := os.Rename(path, path+".bak"); err != nil {
return fmt.Errorf("backup: %w", err)
}
}
return os.WriteFile(path, data, 0o644)
}
func (m *TaskManager) Load(path string) error {
data, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("load %s: %w", filepath.Base(path), err)
}
var tasks []Task
if err := json.Unmarshal(data, &tasks); err != nil {
return fmt.Errorf("load %s: %w", filepath.Base(path), err)
}
m.tasks, m.nextID = tasks, 0
for _, t := range tasks {
m.nextID = max(m.nextID, t.ID)
}
return nil
}
// LoadWithBackup tries the main file first and falls back to the backup.
func (m *TaskManager) LoadWithBackup(path string) (string, error) {
err := m.Load(path)
if err == nil {
return filepath.Base(path), nil
}
if errors.Is(err, fs.ErrNotExist) {
return "", nil // first run: nothing to restore
}
fmt.Println("warning:", err)
if err := m.Load(path + ".bak"); err != nil {
return "", err
}
return filepath.Base(path) + ".bak", nil
}
func main() {
dir, err := os.MkdirTemp("", "taskmgr-backup-*")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "tasks.json")
m := &TaskManager{}
m.Add("Write report")
if err := m.Save(path); err != nil { // first save: no backup yet
fmt.Println(err)
return
}
m.Add("Review pull request")
if err := m.Save(path); err != nil { // old file becomes tasks.json.bak
fmt.Println(err)
return
}
// Simulate a crash in the middle of a write: the file is cut short.
broken := []byte(`[{"id": 1, "title": "Wri`)
if err := os.WriteFile(path, broken, 0o644); err != nil {
fmt.Println(err)
return
}
restored := &TaskManager{}
from, err := restored.LoadWithBackup(path)
if err != nil {
fmt.Println("restore failed:", err)
return
}
fmt.Printf("restored %d task(s) from %s\n", len(restored.tasks), from)
for _, t := range restored.tasks {
fmt.Printf("%d. %s\n", t.ID, t.Title)
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Struct tags plus json.MarshalIndent and json.Unmarshal move tasks to and from a JSON file
- Treat only a missing file as a first run; return an error for a broken one
- Writing a temp file and renaming it means a crash never leaves half a file
- Guard state shared between goroutines with a mutex, and check with -race
- Stop the goroutine with close(done), then wait for its final save with wg.Wait()
A Tour of Go — Go