Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 04 · 45 minutes

Read a file, write JSON and take flags

After this lesson you can
  • 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
Lab files of this lesson (14)

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

PartPackageJob
Lines of a filebufio.ScannerReads one line at a time, so a big file does not fill the memory.
JSONencoding/jsonMarshal turns a value into JSON. Unmarshal turns JSON into a value.
OptionsflagReads -name value from the command line.
Resultos.ExitGives 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.

A field of Finding with a struct tag
Servicefield name: capital, so JSON sees itstringthe type of the fieldjson:"servicethe key in the JSON text,omitempty"leave the key out if emptyServicefield name: capital, so JSON sees itstringthe type of the fieldjson:"servicethe key in the JSON text,omitempty"leave the key out if empty

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.

From a text file to a JSON report
TerminalYour folderShellhosts.txtfindingsreport.json1234TerminalYour folderShellhosts.txtfindingsreport.json1234
  1. Shell → findings: runs it with the flags -in and -out
  2. hosts.txt → findings: read one line at a time, each one checked
  3. findings → report.json: findings written as JSON, mode 0o600
  4. 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
EOT

go 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.22

2. 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:

CallJob
os.OpenOpens the file.
bufio.NewScannerWraps the file. sc.Scan() moves to the next line, and sc.Text() returns it.
strings.TrimSpaceRemoves spaces at both ends.
strings.HasPrefixTests the start of a string.
strings.FieldsSplits a string at the spaces.
strconv.AtoiTurns text into a number (lesson 3).

The loop has three parts, so n is the line number. The loop ends when Scan gives false.

The loop that reads the lines
forstart of a loopn := 1;before the first pass: n is 1sc.Scan();tested before each pass: a line?n++after each pass: n grows by oneforstart of a loopn := 1;before the first pass: n is 1sc.Scan();tested before each pass: a line?n++after each pass: n grows by one

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-alt

Scan 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
7

Writing 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 int

6. 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:

NameJob
flag.StringDefines an option and gives a pointer to its value, so you read it as *in.
flag.ParseReads 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.WriteFileWrites a whole file.
0o600The 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=2

The 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 ops

Then 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.Scanner stops with token too long on a line over 64 KB. A log with a very long line breaks it. Give it a bigger buffer with sc.Buffer, or read with bufio.Reader when 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.Rename it. 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.MaxBytesReader or io.LimitReader. A json.Decoder with DisallowUnknownFields rejects keys that you did not expect, which finds typos in a config file.
  • os.WriteFile sets the permission only when it creates the file. An old file keeps its mode. Check with ls -l, and fix it with os.Chmod.