Lesson 03 · 50 minutes
Handle errors and split code into a package
- Write functions that return an error, and a method that an interface names
- Wrap an error with `%w` and test it with `errors.Is`
- Move code into a package and export only what is needed
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
Your team collects scan targets from many people, and they write them as host:port. Some are wrong: no host, no port, a port that is a word or a number that is too large. A tool that guesses will report a wrong "all clear". You will write a small package that reads one target and fails in a clear way, and that other tools can reuse.
Recall
What does a map give you for a key that is not in it, and how do you tell that the key was missing?
It gives the zero value of the value type. Use value, ok := m[key]: ok is false when the key is missing.
Which command lists the Go files that are not formatted?
gofmt -l . lists them, and gofmt -w file.go repairs a file.
The idea
A Go function can return more than one value. By habit the last value is an error. If the call worked, the error is nil. If not, it holds a description. There are no exceptions in normal code: you check the error with if err != nil.
| Word | Meaning |
|---|---|
error | A built-in type. Any value with an Error() string method is an error. |
| Wrap | Add context to an error and keep the original inside it: fmt.Errorf("...: %w", err). |
| Method | A function that belongs to a type. You call it after the value with a dot: f.Close(). Step 7 writes one. |
| Interface | A list of methods. Any type that has them can be used where the interface is wanted. error is one. Step 7 writes one. |
errors.Is | Asks if an error, or any error that it wraps, is a known one. |
defer | Runs a call when the function ends, in the reverse order of the defers. |
| Exported | A name that starts with a capital letter. Other packages can use it. |
- main → portspec.Parse: Parse("http")
- portspec.Parse → strconv.Atoi: Atoi("http")
- strconv.Atoi → portspec.Parse: error: invalid syntax
- portspec.Parse → main: wraps it with %w and returns it
- main: errors.Is looks inside the wrapper
Worked example
1. Return two values
Make ~/krlab/go/funcs with a module, then write main.go. A function is declared with func, a list of inputs, and the types of what it returns. Two names are new:
| Name | Job |
|---|---|
strings.Cut(s, sep) | From the package strings. Splits s at the first sep and also says if it found one. |
if !found | Runs the block when found is false. |
mkdir -p ~/krlab/go/funcs
cd ~/krlab/go/funcs
go mod init krlab/funcsgo 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/funcs
go 1.22main.go
package main
import (
"fmt"
"strings"
)
func splitTarget(t string) (string, string) {
host, port, found := strings.Cut(t, ":")
if !found {
port = "80"
}
return host, port
}
func main() {
h, p := splitTarget("10.0.0.5:8080")
fmt.Println(h, p)
h, p = splitTarget("example.test")
fmt.Println(h, p)
}go run .10.0.0.5 8080
example.test 80This cut at the first : fails for an IPv6 address such as [::1]:80. For real addresses use net.SplitHostPort and net.JoinHostPort. Lesson 8 uses the second one.
2. Check an error
Replace main.go. The function returns 0, err on failure and n, nil on success. Four names are new:
| Name | Job |
|---|---|
strconv.Atoi | ASCII to integer: turns text into a number and returns an error when it cannot. |
nil | Means "no error". |
fmt.Errorf | Builds a new error from a pattern, as Printf does. |
continue | Skips to the next pass of a loop. |
After each call, the caller takes one of two roads:
- Call the function → Check err: it returns a value and an error
- Check err → Use the value: err is nil: carry on
- Check err → Return the error: err is not nil: wrap it
main.go
package main
import (
"fmt"
"strconv"
)
func parsePort(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, err
}
if n < 1 || n > 65535 {
return 0, fmt.Errorf("port %d is out of range", n)
}
return n, nil
}
func main() {
for _, s := range []string{"443", "http", "70000"} {
port, err := parsePort(s)
if err != nil {
fmt.Println("error:", err)
continue
}
fmt.Println("ok:", port)
}
}ok: 443
error: strconv.Atoi: parsing "http": invalid syntax
error: port 70000 is out of range3. Move the function into a package
A package is a folder. Make the folder portspec and write portspec/portspec.go. Two changes: Parse has a capital letter, and the errors now carry context with %w. These names and marks are new:
| Name | Job |
|---|---|
errors.New | Makes an error value with a fixed text. |
%w in fmt.Errorf | Wraps an error and keeps it inside the new one. |
A capital letter (Parse) | Other packages can call the name. A small letter (valid) keeps it private. |
// right above a name | The documentation of that name. |
mkdir portspecfuncs/portspec/portspec.go
// Package portspec turns text from a user into port numbers.
package portspec
import (
"errors"
"fmt"
"strconv"
)
// ErrRange means a port is outside 1 to 65535.
var ErrRange = errors.New("port out of range")
// Parse converts text such as "443" to a port number.
func Parse(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("parse port %q: %w", s, err)
}
if !valid(n) {
return 0, fmt.Errorf("parse port %q: %w", s, ErrRange)
}
return n, nil
}
func valid(n int) bool {
return n >= 1 && n <= 65535
}4. Test for a known error
The import path is the module name plus the folder. switch with no value picks the first case that is true. errors.Is finds ErrRange inside the wrapped error, so the caller can react to the kind of failure and not to the text of the message.
main.go
package main
import (
"errors"
"fmt"
"krlab/funcs/portspec"
)
func main() {
for _, s := range []string{"443", "http", "70000"} {
port, err := portspec.Parse(s)
switch {
case errors.Is(err, portspec.ErrRange):
fmt.Println("range:", err)
case err != nil:
fmt.Println("other:", err)
default:
fmt.Println("ok:", port)
}
}
}ok: 443
other: parse port "http": strconv.Atoi: parsing "http": invalid syntax
range: parse port "70000": port out of range5. Try the private name
Change main to call portspec.valid(5) and run it. The compiler refuses.
./main.go:10:23: undefined: portspec.validThe words may differ in your version of Go. A package shows only its exported names, so you can change the inside later without breaking its users.
6. Clean up with defer
Replace main.go, and make a small file first. The command cat > note.txt <<'EOT' writes the lines up to EOT into note.txt. defer f.Close() runs when readHead ends, on every path out of it, including each early return. The two defers in main run last first. These calls are new:
| Call | Job |
|---|---|
os.Open | Opens a file. |
f.Read(buf) | Reads bytes into a buffer and returns how many. |
f.Close | Closes the file. |
os.ErrNotExist | A ready-made error value of the package os: the file does not exist. |
Read may give fewer bytes than the buffer holds, and a longer file is cut at 8 bytes, so the function reads only the head of the file. Lesson 4 reads whole lines with bufio.Scanner.
cat > note.txt <<'EOT'
krbox
EOTmain.go
package main
import (
"errors"
"fmt"
"os"
)
func readHead(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", fmt.Errorf("open: %w", err)
}
defer f.Close()
buf := make([]byte, 8)
n, err := f.Read(buf)
if err != nil {
return "", fmt.Errorf("read: %w", err)
}
return string(buf[:n]), nil
}
func main() {
defer fmt.Println("one")
defer fmt.Println("two")
fmt.Println("start")
s, err := readHead("note.txt")
fmt.Printf("%q %v\n", s, err)
_, err = readHead("/no/such/file")
fmt.Println(err)
fmt.Println(errors.Is(err, os.ErrNotExist))
}start
"krbox\n" <nil>
open: open /no/such/file: no such file or directory
true
two
oneerrors.Is works even through the open: wrapper, because %w keeps the original error inside.
7. Give a type a method, and share it through an interface
A method is a function with a receiver: a value in brackets before its name. func (f Finding) String() string is the method String of the type Finding, and you call it as f.String(). An interface lists methods. A type satisfies it when it has all of them: there is no implements keyword. A receiver with no name, as in func (Loopback) Check, means that the method does not use the value. Replace main.go. These names are new:
| Name | Job |
|---|---|
String() string | A method of this exact form. fmt calls it when it prints the value, so Println(f) shows db1:3306. |
fmt.Sprintf | Like Printf, but it returns the text and does not print it. |
type Checker interface { ... } | An interface with one method, Check(host string) string. |
[]Checker | A slice whose items may be of any type that has Check. |
main.go
package main
import "fmt"
// Finding is one open port on one host.
type Finding struct {
Host string
Port int
}
// String is the method that fmt calls to print a Finding.
func (f Finding) String() string {
return fmt.Sprintf("%s:%d", f.Host, f.Port)
}
// Checker decides whether a host may be scanned.
type Checker interface {
Check(host string) string
}
// Loopback allows only this machine.
type Loopback struct{}
func (Loopback) Check(host string) string {
if host == "127.0.0.1" || host == "localhost" {
return "allowed"
}
return "refused"
}
// Listed allows the names in its list.
type Listed struct {
Names []string
}
func (l Listed) Check(host string) string {
for _, n := range l.Names {
if n == host {
return "allowed"
}
}
return "refused"
}
func main() {
f := Finding{"db1", 3306}
fmt.Println(f)
fmt.Printf("%v and %s\n", f, f.String())
checkers := []Checker{Loopback{}, Listed{Names: []string{"db1"}}}
for _, c := range checkers {
fmt.Printf("%T: db1 %s, 127.0.0.1 %s\n", c, c.Check("db1"), c.Check("127.0.0.1"))
}
}go run .db1:3306
db1:3306 and db1:3306
main.Loopback: db1 refused, 127.0.0.1 allowed
main.Listed: db1 allowed, 127.0.0.1 refusedThe loop does not know which type it holds: it only knows that each item has Check. Rename Check to Check2 in Listed and run again. The compiler refuses the slice, because Listed no longer satisfies Checker. Change the name back.
The same idea is all over Go. error is an interface with one method, Error() string, so any type with that method is an error. http.Handler (lesson 5) and io.Reader are interfaces too. A method can also take a pointer receiver, func (s *Server) Stop(), so that it changes the value and not a copy (lesson 4).
Your turn
Write the package for the targets of your team. There are no steps here: use what the worked example showed.
In ~/krlab/go/targets, make the module krlab/targets and the package hostport (a folder of that name). It has one exported function, Parse(s string) (string, int, error), that reads host:port and returns the host and the port number. The rules:
- Text with no
:fails with the exported errorErrNoPort, whose text isport missing. - An empty host fails with
ErrNoHost, whose text ishost missing. - A port that is not a number fails with the error of
strconv.Atoi. - A port below 1 or above 65535 fails with
ErrRange, whose text isport out of range. - Every failure is wrapped with
fmt.Errorf("target %q: %w", s, err), so that the text starts with the target.
Apply the rules in the order of the list. In main.go, call Parse for these six targets and print ok with the host and the port, or error: with the error. Count how many errors match ErrNoHost with errors.Is.
10.0.0.6:22 :80 db1:99999 web1:ssh mail1 api1:8443Check yourself
Why use `%w` and not `%v` in `fmt.Errorf`?
%v copies the text of the error and loses the original. %w keeps the original inside the new error, so errors.Is and errors.As can still find it.
A caller checks `err.Error() == "port out of range"`. What breaks when you add context to the message?
The test fails, because the text is now parse port "70000": port out of range. Compare errors with errors.Is against a named value, not by their text.
In lesson 1 you wrote `host, _ := os.Hostname()`. What is the risk?
The _ drops the error. If the call fails, host is empty and the program goes on as if nothing happened. In a tool that decides about security, check every error.
A type of your own has the method `Error() string`. Where can you use a value of that type?
Anywhere that an error is wanted: return it, wrap it with %w, test it with errors.Is. The type satisfies error because it has the method. It does not need to say so.
Field notes
- Ignore an error only when you can say why.
defer f.Close()on a file that you only read is usual. On a file that you write,Closecan report a lost write, so check its error. - Add context at each layer, once. A good message tells an operator what the tool tried to do, and with what input.
- Do not put secrets in error text. Errors go to logs, and logs go to many places. Log the user name or the host, never the password or the token.
errors.Asfinds a wrapped error of a given type, for example*strconv.NumError, when you need its fields and not only its identity.errors.Join(Go 1.20) combines several errors, which suits a tool that checks many hosts and reports all failures at the end.panicis for bugs that should never happen, not for bad input. A scanner that panics on one strange reply stops the whole scan. Return an error, count it, and continue.