Powerful Command-Line Applications in Go cover

This was a good way to see a number of non-trivial applications in Go. It tackled real projects like a Markdown Previewer and a Port Scanner and used production-grade libraries like Cobra for command-line arguments and Viper for configuration settings. The Markdown Previewer was probably good enough for me to consider using it. Honestly, Cobra and Viper were good enough libraries that it makes me start looking at what my options are for command-line parsing libraries early when studying a new language now. A lot of the examples were big to type, but that is good since it made me feel more comfortable with the language. They were also complicated enough that I made mistakes and got to deal with error messages from the compiler. I will say I was disappointed multiple times that Go’s compiler points out the first error it finds and then stops, so when you fix it you might just be greeted by another error. It’s not like Java or Kotlin where the compiler spits out 10 errors and 5 are probably caused by the earlier errors but the other 5 need to be corrected. The pomodoro app was actually quite usable after I got past the fact that it wouldn’t display correctly in tmux. That was a hard debugging session wondering what was wrong with my output from typing up the code before I finally pinned the blame on running it in a tmux session though, since having a tmux session is just getting so normal to me. Not only did I learn a lot about using Go for small to intermediate-sized projects, but I learned a lot about writing good command-line apps that I can take with me to other languages.

The book starts with a simple word and line counter using flag, decoupling I/O behind io.Reader so you can test it with a bytes.Buffer:

// Chapters 1 and 2 start with standard flag-based word/line counting,
// decoupling I/O using io.Reader so testing with bytes.Buffer is trivial:
func count(r io.Reader, countLines bool) int {
	scanner := bufio.NewScanner(r)
	if !countLines {
		scanner.Split(bufio.ScanWords)
	}

	wc := 0
	for scanner.Scan() {
		wc++
	}
	return wc
}

func main() {
	lines := flag.Bool("l", false, "Count lines")
	flag.Parse()

	fmt.Println(count(os.Stdin, *lines))
}

Projects like the Markdown Previewer (mdp) pull together file I/O, temp files, HTML templates, and launching a browser:

// Chapter 3 builds the Markdown previewer, converting markdown to HTML
// and creating temporary preview files before launching a browser:
func run(filename string, out io.Writer, skipPreview bool) error {
	input, err := os.ReadFile(filename)
	if err != nil {
		return err
	}

	htmlData := parseContent(input)
	tempFile, err := os.CreateTemp("", "mdp*.html")
	if err != nil {
		return err
	}
	defer os.Remove(tempFile.Name())

	if err := saveHTML(tempFile.Name(), htmlData); err != nil {
		return err
	}

	if skipPreview {
		return nil
	}
	return preview(tempFile.Name())
}

By the end, the book walks through full interactive terminal applications like the Pomodoro tool (pomo), backing the terminal UI with a concurrent in-memory repository protected by sync.RWMutex:

// Chapter 9 reaches the interactive Pomodoro tool, backing the terminal UI
// with a thread-safe in-memory repository protected by sync.RWMutex:
type inMemoryRepo struct {
	sync.RWMutex
	intervals []pomodoro.Interval
}

func NewInMemoryRepo() *inMemoryRepo {
	return &inMemoryRepo{
		intervals: []pomodoro.Interval{},
	}
}

func (r *inMemoryRepo) Create(i pomodoro.Interval) (int64, error) {
	r.Lock()
	defer r.Unlock()

	i.ID = int64(len(r.intervals)) + 1
	r.intervals = append(r.intervals, i)
	return i.ID, nil
}

func (r *inMemoryRepo) ByID(id int64) (pomodoro.Interval, error) {
	r.RLock()
	defer r.RUnlock()

	if id == 0 || int(id) > len(r.intervals) {
		return pomodoro.Interval{}, fmt.Errorf("%w: %d", pomodoro.ErrInvalidID, id)
	}
	return r.intervals[id-1], nil
}