Skip to content

Go Beyond the Basics

Glossary

140 terms from Go Beyond the Basics, in plain words, each with the chapter that teaches it.

#

%+v
A `fmt` formatting verb that prints a struct along with its field names, which is handy for checking what `json.Unmarshal` filled in.

A

any
A constraint that every type satisfies. As a type, it holds a value of any type, as with the `v any` parameter of `writeJSON`.
API (application programming interface)
A set of URLs and rules that other programs use to talk to your service. Kettle & Crane's order service is an API that the website and cafés call.
atomic
An operation done in one step that no other goroutine can see half finished. `atomic.Int64` is a counter you can update from many goroutines without a mutex, such as counting page views.

B

block
To wait and not return until something happens. `wg.Wait()` blocks until every goroutine is done, and a channel send blocks until someone receives.
body
The data sent with an HTTP request or response, after the headers. An order's JSON is the body of the POST request.
bubble
The isolated group of goroutines that `synctest.Test` runs with a fake clock. When all of them are waiting, the clock jumps to the next timer.
buffered channel
A channel with room for a few values, made with `make(chan int, 3)`. Sends wait only when it is full, and receives wait only when it is empty.

C

cap / capacity
How many elements a slice or channel has room for. `make([]int, 0, 10)` is empty but has capacity 10, and `cap` reports it.
channel
A typed pipe that goroutines use to send values to each other. `chan int` carries `int`s, and a send and a receive are needed for each hand-over.
client
The program that sends an HTTP request and waits for the answer, such as curl or a browser.
close
A built-in that marks a channel as finished. Receivers still get any values left, then stop. Only the sender should close a channel, since sending on a closed one panics.
closure
A function literal that uses and can change variables from the code around it. `counter()` returns a closure that remembers its own `n`.
cmp.Ordered
A constraint from package `cmp` for types that work with `<` and `>`: integers, floats and strings.
comma-ok
A form like `v, ok := <-ch` that gives a second `bool` saying whether the operation really produced a value. For a closed, empty channel, or a missing map key, `ok` is false.
comparable
A constraint for types that work with `==`. Map keys must be comparable, so `Set[T comparable]` can use `T` as a map key.
concurrency
Having several jobs in progress at once, like a barista steaming milk while the espresso runs. It is not the same as doing them at the same instant.
constraint
The rule listing which types a type parameter may stand for, such as `int | float64` or `cmp.Ordered`.
Content-Type
A header saying what kind of data the body holds, such as `application/json`. `writeJSON` sets it so clients know to read JSON.
context (context.Context)
A value passed to slow functions that carries a deadline and a cancel signal, telling the work when to stop. Contexts form a tree, so canceling a parent ends its children.
context.Canceled
The error `ctx.Err()` returns after `cancel()` has been called.
context.DeadlineExceeded
The error `ctx.Err()` returns when a context's time limit has run out.
critical section
The code between `Lock` and `Unlock`, which only one goroutine may run at a time. Keep it short so others don't wait long.
Ctrl+C
The keyboard shortcut that sends an interrupt signal to a running program. In Go, `signal.NotifyContext` turns it into a canceled context so the program can stop tidily.
ctx.Done()
A channel that is closed when the context ends, so a `select` can wait on it alongside the real work.
ctx.Err()
Says why a context ended: `context.Canceled` or `context.DeadlineExceeded`. It returns nil while the context is still live.
curl
A command-line tool that sends HTTP requests, used to try out the server. `-i` shows the headers, and `-d` sends a body as a POST.

D

data race
Two goroutines using the same variable at once, with at least one writing. It depends on timing, so it can hide in tests, as with the shop selling 20 of 9 mugs; Go sometimes stops with `fatal error: concurrent map writes`.
deadlock
A state where every goroutine is waiting and none can go on, so Go stops the program with `all goroutines are asleep`.
default (in select)
A `select` case that runs at once when no other case is ready, which makes a send or receive non-blocking.
defer
A keyword that schedules a function call to run when the surrounding function returns, however it returns. It is used for `cancel()`, `mu.Unlock()` and `ticker.Stop()`.
defined type
A new named type built on another, such as `type Cents int`. It behaves like `int` but its name says what the number means.
digit separator
An underscore inside a number, as in `1_000_000`, that Go ignores. It only makes long numbers easier to read.
directional channel
A channel type limited to one direction: `chan<- T` can only send and `<-chan T` can only receive. The compiler enforces it.
DisallowUnknownFields
A JSON decoder setting that makes decoding fail on names the struct doesn't have, which catches typos like `line` for `lines`.
done channel
A channel closed to tell goroutines to stop, usually `chan struct{}`. One `close` reaches every receiver at once.

E

empty struct
A type with no fields that takes no memory, used for channels that signal and carry no data.
encoding/json
Go's standard package for converting between Go values and JSON, with `Marshal`, `Unmarshal`, encoders and decoders.
environment variable
A named setting the shell passes to a program, such as `LOG_LEVEL=debug`. A Go program reads it with `os.Getenv`, which returns `""` if it is unset.
errgroup
A package from golang.org/x/sync that runs functions in goroutines and lets them return errors. `Wait` waits for all of them and returns the first error.
errgroup.WithContext
Makes an errgroup plus a context that is canceled as soon as any goroutine returns an error, so the others can stop early.
errors.As
Searches an error and everything it wraps for an error of a given type, and fills your variable with it. Use it to read fields such as `StockError.Have`.
errors.Is
Checks whether an error, or any error it wraps, is a particular sentinel such as `ErrSoldOut` or `context.DeadlineExceeded`.
errors.Join
Combines several errors into one so you can report every problem at once. It skips nil errors, and `errors.Is` still finds each original.
exit code
A number a program returns when it ends. 0 means success, and non-zero such as 1 tells scripts it failed.

F

fmt.Fprintln / fmt.Fprintf
Versions of `Println` and `Printf` that write to any `io.Writer` you pass, such as an HTTP response.
for range over a channel
`for v := range ch` receives values from a channel until it is closed and empty. With no variable, `for range n` just repeats `n` times.
function literal
A function written without a name, right where it is needed, such as `func(cents int) int { return cents / 2 }`.
function value
A function stored in a variable or passed as an argument, like a number. Its type lists parameter and result types, e.g. `func(int) int`.

G

g.SetLimit(n)
Caps how many of an errgroup's goroutines run at once. It must be called before the first `g.Go`, which then waits while `n` are running.
generic type
A type with type parameters, such as `Set[T comparable]`. Its methods repeat the parameters in the receiver, like `(s *Set[T])`.
generics
Writing code once with a blank for the type, so one function or type works for many types, such as `Sum` for both `int` and `float64`.
Git Bash
A Bash shell for Windows that is installed with Git for Windows. It lets Windows users run Unix-style commands such as `curl` exactly as they are written for macOS and Linux, unlike PowerShell, where `curl` is a different command.
go get / go mod init
`go mod init` creates a module (a project with its own dependency list), and `go get` adds an outside package such as `errgroup` to it.
go test / go vet
`go test` runs your tests, and `-v` lists each test and subtest. `go vet` checks code for likely mistakes, such as copying a mutex or ignoring a `cancel` function.
goroutine
A function running alongside the rest of the program, started with the `go` keyword. Goroutines are cheap, but they all stop when `main` returns.

H

handler (HTTP)
A function that answers an HTTP request, with the form `func(w http.ResponseWriter, r *http.Request)`. The request comes in as `r` and the response goes out through `w`.
handler (slog)
The part of a slog logger that decides how events are written, as `key=value` text or as JSON. It is unrelated to an HTTP handler.
headers
Name-value lines sent before the body of a request or response, such as `Content-Type: application/json`.
HTTP (HyperText Transfer Protocol)
The protocol programs use to talk over the web. A client sends a request with a method (GET reads, POST sends something new) and the server replies with a status, headers and body.
http.Error
Writes a status code and a plain-text message as the response, e.g. `http.Error(w, "no such product", http.StatusNotFound)`.
http.ErrServerClosed
The error `ListenAndServe` returns after a deliberate shutdown. It should be treated as success.
http.Handler
An interface: anything with a `ServeHTTP(w, r)` method, such as the router. Middleware takes one and returns another.
http.HandlerFunc
A conversion that turns a plain handler function into an `http.Handler`, so it can be wrapped by middleware.
http.MaxBytesReader
A Go function that wraps a request body so that reading stops with an error after a set number of bytes, such as 64 KB. It stops clients from sending huge bodies that would use up the server's memory.
http.Server
A struct that configures a web server, with an address and timeouts for reading the request, writing the response and idle connections. A slow client can't hold a connection forever.
httptest
A package for testing handlers without a network. `NewRequest` makes a fake request and `NewRecorder` captures the status code and body.

I

in-memory
Data kept only in the running program's memory, so a restart loses it. The order service's stock resets on restart.
int64
An integer type that is always 64 bits wide, the type held by `atomic.Int64`.
io.Discard
An `io.Writer` that throws away everything written to it, used to silence logs in tests.
io.Reader
Anything you can read bytes from, meaning anything with a `Read` method, such as a request body.
io.Writer
Anything you can write bytes to, meaning anything with a `Write` method, such as an HTTP response, a file or the terminal.

J

JSON (JavaScript Object Notation)
A text format for data using objects in braces, arrays in brackets, strings, numbers, `true`, `false` and `null`. It is the usual format for web APIs.
json.Marshal / json.Unmarshal
`Marshal` turns a Go value into JSON bytes, and `Unmarshal` fills a Go value from JSON (give it a pointer). `MarshalIndent` does the same as `Marshal` with one field per line for people.
json.NewEncoder / json.NewDecoder
An encoder writes JSON to an `io.Writer`, and a decoder reads JSON from an `io.Reader`. They are how handlers send and receive JSON.

L

localhost
The computer's name for itself. A server at `localhost:8080` accepts connections only from the same machine.
log
The standard package that prints lines with the date and time in front. `log.Fatal` prints and then exits.
log level
How serious a log line is: Debug (details for finding bugs), Info (normal events), Warn (something odd) or Error (a failure). A minimum level hides less important lines.

M

make
A built-in that creates a ready-to-use channel, slice or map, e.g. `make(chan int)`, `make([]int, 0, 10)` or `make(map[string]int)`.
method value
A method named without calling it, such as `s.handleOrder`. It is a function with its receiver already built in, so a handler can reach the store.
middleware
A function that wraps a handler to do work before or after it, such as `logRequests` timing and logging every request.
mutex
A lock that lets one goroutine at a time into a critical section. `mu.Lock()` waits if someone holds it, and `defer mu.Unlock()` releases it. It prevents the shop from overselling.

N

net/http
Go's standard package for HTTP servers and clients, with a router, handlers and `http.Server`.
nil map
A map declared with `var m map[string]int` but never made. Writing to it panics, so create maps with `make`.
non-blocking
A send or receive that gives up at once instead of waiting, made with a `select` that has a `default` case.

O

omitempty
A JSON struct-tag option that leaves a field out when it has its zero value, as in `json:"notes,omitempty"`.
os.Stdout
Standard output, which is normally the terminal, as an `io.Writer`. `fmt.Println` prints there.

P

panic
A runtime failure that stops the program, such as writing to a nil map or sending on a closed channel. `net/http` catches a handler's panic, but a panic in a goroutine you start crashes the whole program.
parallelism
Work happening at the same instant on several CPU cores. Go gives you concurrency, and parallelism when the cores exist.
path
The part of a URL after the host, such as `/orders/1` or `/products/HE-5LB`.
pattern
A route given to the router, such as `"GET /products/{sku}"`: a method, a space and a path, which may include wildcards.
pointer receiver
A method declared on `*T` instead of `T`, so it works on the original value rather than a copy. Mutex-holding types need it, since a copied mutex guards nothing.
port
A number that identifies one server program on a computer, like a numbered door. For example, the Kettle & Crane order service listens on port 8080.

Q

query string
The part of a URL after `?`, such as `max=1500` in `/products?max=1500`. A handler reads it with `r.URL.Query().Get("max")`.

R

r.Context()
The context attached to an HTTP request. It is canceled if the client goes away, so slow handler work can stop early.
race detector
A tool switched on with `-race` on `go run`, `go build` or `go test` that reports data races while the program runs. It is slow, so use it in tests and development.
raw string
A string in backquotes, taken exactly as written, so quotes and backslashes are ordinary characters. It suits JSON.
receive
Taking a value from a channel with `<-ch`. It waits until a value is there.
recover
A built-in that, when called in a deferred function, stops a panic and returns its value (nil if there was no panic). It guards goroutines you start yourself.
request
What a client sends: a method, a path, headers and sometimes a body.
response
What a server sends back: a status code, headers and a body.
router
The part that picks which handler runs for each request. `http.NewServeMux` makes one.
RWMutex
A lock that lets any number of readers in at once, or a single writer. It suits data read often and changed rarely, like a price list.

S

select
A statement that waits on several channel operations and runs the case of the first one that is ready, picking randomly if several are. It looks like a `switch`.
send
Putting a value into a channel with `ch <- v`. On an unbuffered channel it waits for a receiver.
sentinel error
A package-level error value, like `ErrSoldOut` or `ErrNotFound`, that callers compare with `errors.Is`.
server
A program that waits for requests and answers them, such as Kettle & Crane's order service.
signal.NotifyContext
Returns a context that is canceled when the program gets a signal such as Ctrl+C, plus a `stop` function used like `cancel`.
slog (log/slog)
Go's package for structured logging. `slog.Info("msg", "key", value)` logs a message with key-value pairs at a level.
slog.HandlerOptions
Settings for a slog handler, such as the minimum `Level`. Pass `&slog.HandlerOptions{Level: slog.LevelDebug}` to see Debug lines.
slog.Logger
A logger made by `slog.New` from a handler, with `Info`, `Debug`, `Warn`, `Error` and `With`. `With` returns a new logger that adds pairs to every event.
slog.New / NewTextHandler / NewJSONHandler
`NewTextHandler` writes `key=value` lines and `NewJSONHandler` writes one JSON object per line. `slog.New` makes a logger from either.
srv.Shutdown
Stops an `http.Server` cleanly: it takes no new connections and waits for running requests to finish, within the context's time limit.
status code
The number in an HTTP response that says how the request went. Common ones are 200 OK (it worked), 201 Created (a new thing was made), 400 Bad Request (bad input), 404 Not Found (no such thing), 405 Method Not Allowed (wrong method), 409 Conflict (clashes with current state, such as too little stock) and 500 Internal Server Error (the server failed).
strings.NewReader
Makes an `io.Reader` from a string, useful for giving a test request a body.
struct tag
A note in backquotes after a struct field, such as `json:"price_cents"`, that packages like `encoding/json` read to name the JSON field.
structured logging
Writing each log event as a message plus key-value pairs, like `method=GET path=/health`, so a tool can search them.
subtest
A named test inside a test, started with `t.Run(name, f)`. A failure then says which row broke.

T

t.Parallel
Lets a test or subtest run alongside other parallel ones. It is safe only if the tests don't change shared data.
table-driven test
A test that loops over a list of cases (a table), each with inputs and the expected result, so adding a case is one new row.
testing/synctest
A package that runs a test in a bubble with a fake clock, so waits take no real time and the test doesn't flake on a busy machine.
ticker
Something that sends the time on a channel at a fixed interval. Call `Stop` when done, usually with `defer`.
tilde (~)
In a constraint, `~int` means any type whose underlying type is `int`, which lets `Sum` accept `[]Cents`.
time.After / time.NewTicker
`time.After(d)` gives a channel that receives once after `d`, and `time.NewTicker(d)` gives one that receives every `d`. Both are used in `select`.
time.Duration
A length of time, built by multiplying units such as `300 * time.Millisecond`.
time.Sleep / time.Now / time.Since
`time.Sleep(d)` pauses for `d`, `time.Now()` reads the clock, and `time.Since(start)` gives the time elapsed since `start`.
timeout
A limit on how long to wait. In Go you make one with `time.After` in a `select`, with `context.WithTimeout`, or with the `http.Server` timeouts.
type argument
The actual type supplied for a type parameter, such as `string` in `NewSet[string]()`.
type inference
Go working out a type argument from the values you pass, so you can write `Sum(xs)` instead of `Sum[int](xs)`. It fails when the type appears only in the result.
type parameter
A placeholder for a type, written in square brackets after a function or type name, as in `Sum[T int | float64]`.

U

unbuffered channel
A channel with no room, made with `make(chan T)`, where every send waits for a receive.
underlying type
The type a defined type is built on. `Cents` has underlying type `int`, and `~int` matches every such type.
unexported field
A struct field whose name starts with a lowercase letter, so other packages can't see it. `encoding/json` skips unexported fields, such as `cost`.
union
A constraint that allows any of several listed types, written with `|`, such as `int | float64`.

W

WaitGroup
A counter from package `sync` that waits for a group of goroutines. `wg.Go(f)` starts and counts a goroutine, and `wg.Wait()` blocks until all have finished.
wildcard
A `{name}` part of a route pattern, like `{sku}` in `/products/{sku}`. A handler reads the matched text with `r.PathValue("sku")`.
WithTimeout / WithCancel
Each makes a child context plus a `cancel` function. `WithTimeout` ends after a time, and `WithCancel` ends only when you call `cancel`, which you should always do, usually with `defer`.
worker pool
A fixed number of goroutines (workers) taking jobs from one channel and sending results on another, like Alex's three packers sharing eight orders.
wrapping errors (%w)
`fmt.Errorf("...: %w", err)` makes a new error that adds context but keeps the original inside, so `errors.Is` and `errors.As` can still find it.

Z

zero value
The default value a variable or element has when nothing is set: 0 for numbers, `""` for strings, `false` for bools and `nil` for maps. A receive from a closed, empty channel gives one.