Capstone 1: the command line tool
The command is the library with a shell around it: read a document from a file or standard input, parse it, write it back compact or indented, and exit with a status the shell can test. It is the smallest useful command a Go program can be, and it uses the flag package from lesson 84 and the errors from lesson 117.
The command
main declares one flag, reads the file or the stdin, parses, and prints. Every failure is a message on stderr and exit status 2, including the one about the arguments. The file is cmd/jq/main.go in the module.
package main
import (
"flag"
"fmt"
"io"
"os"
"example.com/jsonx/jsonx"
)
func main() {
indent := flag.Bool("indent", false, "indent the output")
flag.Usage = func() {
fmt.Fprintln(os.Stderr, "usage: jq [-indent] [file]")
flag.PrintDefaults()
}
flag.Parse()
var src []byte
var err error
if flag.NArg() > 0 {
src, err = os.ReadFile(flag.Arg(0))
} else {
src, err = io.ReadAll(os.Stdin)
}
if err != nil {
fmt.Fprintln(os.Stderr, "jq:", err)
os.Exit(2)
}
value, err := jsonx.Parse(src)
if err != nil {
fmt.Fprintln(os.Stderr, "jq:", err)
os.Exit(2)
}
fmt.Println(string(value.JSON()))
if *indent {
fmt.Println(string(value.Indent(" ")))
}
}
The command is forty lines because the work is in the package. That is the layout to aim for: a command reads the environment, calls the library and maps its errors to a status, and a test of the library never starts a process.
A flag and a file
The sample file holds an object with an id, a title, tags and a done flag. The indented run prints the compact form first and then the indented one, which is what the command does by design: a script that pipes the output gets one line, and a person who asked for the indented form gets both.
go build -o jq ./cmd/jq && ./jq -indent sample.json
{"done":false,"id":1,"tags":["home","errand"],"title":"buy milk"}
{
"done": false,
"id": 1,
"tags": [
"home",
"errand"
],
"title": "buy milk"
}
The keys are sorted, so the output does not depend on the order of the input: a document with the same fields in another order produces the same bytes. That is a property worth having in a formatter, because a diff of two files then shows the values that changed and not the reordering.
A file or stdin
With no file argument the command reads standard input, which is what makes it usable in a pipe. The run below prints the compact form of a document with two fields.
echo '{"b": 2, "a": [1, 2]}' | ./jq
{"a":[1,2],"b":2}
The pipe is the reason io.ReadAll(os.Stdin) is the fallback: a command that only accepted a file would be useless in a pipeline. The input is read whole because a document is small; a stream of documents would use the decoder from lesson 89 and a loop.
An error and the status
A missing file is a message and a status, not a panic. The command prints jq: and the error on standard error and exits 2, which a shell reads as a failure and a script can test.
./jq missing.json ; echo "exit status: $?"
jq: open missing.json: no such file or directory
exit status: 2
A parse error takes the same path and prints the position: jq: line 1, column 9: trailing comma in object. The usage line is the flag package's, printed by -h with status 0; the command adds the syntax in its own usage function.
A thin wrapper
The command knows about files, flags and exit codes; the package knows about JSON. A function that did both would be testable only through a process, and the status would be the only thing a test could see. The split is the reason the forty lines of the command are boring, and boring is the goal.
The last lesson of the part measures the library against encoding/json and reports the result honestly, including where the standard library wins.
Exercises
- Add a -compact flag that prints only the compact form. Which lines of main change, and what does the indented run print then?
- Make the command accept several files and process them in order. What does it print for a file that fails, and what status does it exit with?
- Read a stream of documents from stdin with json.Decoder instead of ReadAll. Which loop do you need, and how does it detect the end?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Where does the command live?
Answer
In cmd/jq, a package main
A command per directory under cmd.
-
What does the command read with no file argument?
Answer
Standard input
It makes the tool usable in a pipe.
-
What is the exit status of a missing file?
Answer
2
The shell sees a failure.
-
Where does an error message go?
Answer
Standard error
Standard output stays machine-readable.
-
Why does the tool print both forms with -indent?
Answer
A pipe gets one line and a person gets both
The compact line is for scripts.
-
Why are the output keys sorted?
Answer
The value constructor sorts them, so the bytes are stable
A diff shows the values, not the order.
-
What does -h print and exit with?
Answer
The usage on stderr, status 0
Asking for help is not an error.
-
Why keep the JSON code out of main?
Answer
A library can be tested without a process
The command is only I/O and status.
-
Why read the whole input?
Answer
A document is small; a stream would use a decoder loop
The lesson names the alternative.
-
What does a parse error print?
Answer
The position and the message on stderr
It comes from the error type.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev