Lesson 04 · 45 minutes
Read a file, write JSON and take flags
- Read a text file line by line and write a file
- Convert a struct to JSON and back with struct tags
- Build a command line with the `flag` package and exit codes
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
A teammate sends you a plain text list of hosts and ports. The dashboard of your team wants the same data as JSON, and a nightly job must stop if the file is wrong. You will build findings, a small tool that reads the text list, writes a JSON report, and tells the shell with an exit code if it worked. Then you build a second tool of your own for a different list.
Recall
In lesson 3 you wrapped an error with `%w`. What does `errors.Is` do with the wrapped error?
It looks inside the wrapper for a known error value, such as portspec.ErrRange, so the caller can react to the kind of failure and not to its text.
What happens to a struct when you assign it to a new variable?
It is copied. A change to the copy does not touch the original (lesson 2: g := f, then g.Port = 2222).
The idea
| Part | Package | Job |
|---|---|---|
| Lines of a file | bufio.Scanner | Reads one line at a time, so a big file does not fill the memory. |
| JSON | encoding/json | Marshal turns a value into JSON. Unmarshal turns JSON into a value. |
| Options | flag | Reads -name value from the command line. |
| Result | os.Exit | Gives the shell a number. 0 means success. |
A struct tag is a note after a field. It sets the name of the field in JSON. Only exported fields (capital letter) take part in JSON.
An exit code is the number a program returns to the shell. By habit: 0 success, 1 a failure while running, 2 wrong use of the command line.
- Shell → findings: runs it with the flags -in and -out
- hosts.txt → findings: read one line at a time, each one checked
- findings → report.json: findings written as JSON, mode 0o600
- findings → Shell: exit code: 0 worked, 1 failed, 2 wrong use
Worked example
1. Make the folder and an input file
cat > hosts.txt <<'EOT' writes the lines up to EOT into hosts.txt. The quotes around EOT make the shell write the text exactly as printed.
mkdir -p ~/krlab/go/filesjson
cd ~/krlab/go/filesjson
go mod init krlab/filesjson
cat > hosts.txt <<'EOT'
# host port service
10.0.0.5 22 ssh
10.0.0.7 3306 mysql
10.0.0.9 8080 http-alt
EOTgo mod init writes this go.mod. The lab zip holds it with go 1.22, so that it builds on every Go from 1.22:
go.mod
module krlab/filesjson
go 1.222. Read the file line by line
Write read.go. A # at the start of a line marks a comment in this file format. read.go and main.go are in the same package (package main), so main.go can call readFindings with no import. The function skips blank and comment lines, splits each line and returns a slice of Finding. A bad line gives an error with the file name and the line number. It uses these calls:
| Call | Job |
|---|---|
os.Open | Opens the file. |
bufio.NewScanner | Wraps the file. sc.Scan() moves to the next line, and sc.Text() returns it. |
strings.TrimSpace | Removes spaces at both ends. |
strings.HasPrefix | Tests the start of a string. |
strings.Fields | Splits a string at the spaces. |
strconv.Atoi | Turns text into a number (lesson 3). |
The loop has three parts, so n is the line number. The loop ends when Scan gives false.
read.go
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
type Finding struct {
Host string `json:"host"`
Port int `json:"port"`
Service string `json:"service,omitempty"`
}
func readFindings(path string) ([]Finding, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
var out []Finding
sc := bufio.NewScanner(f)
for n := 1; sc.Scan(); n++ {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
fields := strings.Fields(line)
if len(fields) < 2 {
return nil, fmt.Errorf("%s:%d: want host and port", path, n)
}
port, err := strconv.Atoi(fields[1])
if err != nil {
return nil, fmt.Errorf("%s:%d: bad port: %w", path, n, err)
}
fd := Finding{Host: fields[0], Port: port}
if len(fields) > 2 {
fd.Service = fields[2]
}
out = append(out, fd)
}
return out, sc.Err()
}Now main.go prints what it read. fmt.Fprintln(os.Stderr, ...) prints to the error stream, which is for messages and not for results. os.Exit(1) ends the program with exit code 1.
main.go
package main
import (
"fmt"
"os"
)
func main() {
list, err := readFindings("hosts.txt")
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
for _, f := range list {
fmt.Println(f.Host, f.Port, f.Service)
}
}go run .10.0.0.5 22 ssh
10.0.0.7 3306 mysql
10.0.0.9 8080 http-altScan returns false at the end of the file and on a read error. Only sc.Err() tells them apart.
3. Turn the findings into JSON
encoding/json turns Go values into JSON text and back. json.MarshalIndent writes JSON with line breaks. Its second argument is put at the start of each line (empty here), and its third is the indent for each level (two spaces here). The tags in Finding set the names host, port and service. omitempty leaves the key out when the value is empty. A field with a small letter, such as note string, would not be exported, so JSON would ignore it. Replace main.go.
main.go
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
list, err := readFindings("hosts.txt")
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
data, err := json.MarshalIndent(list, "", " ")
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
fmt.Println(string(data))
}[
{
"host": "10.0.0.5",
"port": 22,
"service": "ssh"
},
{
"host": "10.0.0.7",
"port": 3306,
"service": "mysql"
},
{
"host": "10.0.0.9",
"port": 8080,
"service": "http-alt"
}
]4. Meet pointers
The next two steps use pointers. A pointer holds the address of a variable, not its value. &x takes the address of x. *p reads, or writes, the value that p points to. In a type, *int means "a pointer to an int", and *T means the same for any type T. A function takes a pointer when it must change the variable of its caller. Replace main.go.
main.go
package main
import "fmt"
func addOne(n *int) {
*n = *n + 1
}
func main() {
x := 5
p := &x
*p = 6
fmt.Println(x, *p)
addOne(&x)
fmt.Println(x)
}6 6
7Writing through p changed x, and so did addOne. Without the pointer, addOne would change a copy.
5. Read JSON back, and meet a bad input
json.Unmarshal fills a struct from JSON text. Pass a pointer (&f), so that it can write into your variable. Backquotes make a string that can hold double quotes. A key that the struct does not know (banner) is ignored. A value of the wrong type is an error.
main.go
package main
import (
"encoding/json"
"fmt"
)
func main() {
text := `{"host": "10.0.0.5", "port": 22, "banner": "OpenSSH"}`
var f Finding
err := json.Unmarshal([]byte(text), &f)
fmt.Printf("%+v %v\n", f, err)
bad := `{"host": "10.0.0.5", "port": "22"}`
err = json.Unmarshal([]byte(bad), &f)
fmt.Println(err)
}{Host:10.0.0.5 Port:22 Service:} <nil>
json: cannot unmarshal string into Go struct field Finding.port of type int6. Add flags and exit codes
Replace main.go with the finished tool. The work is in run, which returns an error. main reads the flags and chooses the exit code, so os.Exit is in one place: it ends the program at once and skips every defer. These names are new:
| Name | Job |
|---|---|
flag.String | Defines an option and gives a pointer to its value, so you read it as *in. |
flag.Parse | Reads the command line. |
flag.NArg(), flag.Arg(0) | The number of words left after the flags, and the first of them. |
flag.Usage() | Prints the help text. |
os.WriteFile | Writes a whole file. |
0o600 | The permission of the new file: the three digits are owner, group and others, and 6 is read and write, so only you can read it. A list of open ports is a map for an attacker. |
append(data, '\n') | Adds a final line end. |
main.go
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
)
func run(in, out string) error {
list, err := readFindings(in)
if err != nil {
return err
}
data, err := json.MarshalIndent(list, "", " ")
if err != nil {
return err
}
if err := os.WriteFile(out, append(data, '\n'), 0o600); err != nil {
return err
}
fmt.Printf("wrote %d findings to %s\n", len(list), out)
return nil
}
func main() {
in := flag.String("in", "hosts.txt", "text file: one host, port and optional service per line")
out := flag.String("out", "report.json", "JSON file to write")
flag.Parse()
if flag.NArg() > 0 {
fmt.Fprintln(os.Stderr, "unexpected argument:", flag.Arg(0))
flag.Usage()
os.Exit(2)
}
if err := run(*in, *out); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}7. Run it and read the exit codes
echo $? prints the exit code of the last command.
go build -o findings .
./findings -out out.json; echo "exit=$?"
./findings -in nothere.txt; echo "exit=$?"
./findings -bogus; echo "exit=$?"wrote 3 findings to out.json
exit=0
error: open nothere.txt: no such file or directory
exit=1
flag provided but not defined: -bogus
Usage of ./findings:
-in string
text file: one host, port and optional service per line (default "hosts.txt")
-out string
JSON file to write (default "report.json")
exit=2The flag package printed the usage and chose exit code 2 by itself.
Your turn
Build inventory, a tool for a different list. There are no steps here: use what the worked example showed.
In ~/krlab/go/assets, make the module krlab/assets and create two input files. First assets.txt:
assets/assets.txt
# name port owner
web1 80 ops
db1 5432 data
cache1 6379
mail1 25 opsThen bad.txt, with two lines: web1 80 and web2 eighty.
The tool reads the file that -in names (default assets.txt) and writes the JSON file that -out names (default assets.json). Each asset becomes an object with the keys name, port and owner. A missing owner must leave out the key owner. The error text of a bad line has the form file:line: bad port: ..., as in the worked example. A missing input file gives exit code 1, and an extra word on the command line gives exit code 2.
Build it, run it on both files, and run it once with the extra word now.
Check yourself
Why is `Port` in `Finding` written with a capital P, though the JSON key is `port`?
encoding/json sees only exported fields, and an exported name needs a capital letter. The tag json:"port" sets the key in the JSON text.
What is wrong with `defer f.Close()` followed by `os.Exit(1)` in the same function?
os.Exit ends the program at once, and the deferred call never runs. Return an error up to main and call os.Exit there, as run does.
You add the field `note string` to `Finding`. Does it appear in the JSON output?
No. Its name starts with a small letter, so it is not exported, and encoding/json cannot see it.
Field notes
bufio.Scannerstops withtoken too longon a line over 64 KB. A log with a very long line breaks it. Give it a bigger buffer withsc.Buffer, or read withbufio.Readerwhen you cannot trust the line length.- Write a report in a way that a crash cannot leave half a file: write to a temporary file in the same folder, then
os.Renameit. A rename is atomic on one file system, so a reader sees the old file or the new one. - Treat JSON from outside as hostile. Limit the size with
http.MaxBytesReaderorio.LimitReader. Ajson.DecoderwithDisallowUnknownFieldsrejects keys that you did not expect, which finds typos in a config file. os.WriteFilesets the permission only when it creates the file. An old file keeps its mode. Check withls -l, and fix it withos.Chmod.