Learnings

Go, part 6 of 6

Go Standard Library for Backend Work

The packages a backend engineer uses every day, each as one small program with its real output: encoding/json, net/http servers and clients, database/sql, files and io, time, slog, flag and testing. Written for a Python developer; every runnable program was run on Go 1.27 with the standard library only.

JSON

Part 1 of 6 · encoding/json between structs and bytes

Marshal, Unmarshal and struct tags

JSON

Only exported fields take part. The tag json:"name" sets the key, json:"-" hides a field.

Tags name the keys in both directions; Unmarshal needs a pointer.
  • A type mismatch is an error; a missing key leaves the field at its zero value. Tags: struct tags.

Interview point: a lowercase field is silently skipped in both directions. "My JSON is empty" is almost always an unexported field.

omitempty, omitzero, nil vs empty slice

JSON

Options after the key name decide when a field is left out.

OptionDrops the field when
omitemptyfalse, 0, "", nil pointer or interface, empty slice or map. Never a struct, so a zero time.Time is still written.
omitzero (Go 1.24+)the value is the zero value, or its IsZero() method says so. Works for time.Time and structs.

Interview point: a nil slice marshals to null, an empty slice to []. API clients usually want [], so start lists with out := []T{}.

Unknown fields and numbers in any

JSON

By default Unmarshal is forgiving: unknown keys are ignored and key names match without regard to case. Decoding into any gives map[string]any, []any, float64, string, bool and nil.

Interview point: every number decoded into any is a float64, so integers above 253 lose digits. Decode into a struct with int64 fields instead.

json.RawMessage: decode part of it later

JSON

A RawMessage field keeps its JSON as bytes. Read the envelope first, then decode the payload into the type the envelope names.

Custom MarshalJSON and UnmarshalJSON

JSON

A type controls its own JSON form by implementing json.Marshaler and json.Unmarshaler. Here Rupees is an int in Go and a string on the wire.

  • MarshalJSON on the value receiver, UnmarshalJSON on the pointer receiver (it must modify the value).
  • Never call json.Marshal(r) on the same type inside its own MarshalJSON: that recurses forever. Convert to a plain type first.

time.Time in JSON

JSON

time.Time marshals as an RFC 3339 string and only accepts that format back.

  • For a date-only or Unix-seconds field, wrap time.Time in your own type and write the two methods from the previous chapter.
  • Compare instants with Equal, not == (see time zones).

Streaming with Decoder and Encoder

JSON

Decoder reads values one at a time from any io.Reader; Encoder writes to any io.Writer. This is how HTTP handlers read bodies and write responses.

  • Encode adds a newline after each value; Marshal does not.
  • Map keys are written in sorted order, so output is stable.

Version 2: Go 1.27 also ships encoding/json/v2, importable with no build flag. Checked on 1.27.2: its Marshal writes a nil slice as [] and a nil map as {}, key matching is case-sensitive, and a duplicate key is an error. This page uses the classic package, which most code still imports.

HTTP servers

Part 2 of 6 · net/http from one handler to a small accounts API

Handler and HandlerFunc

HTTP servers

Everything in net/http is an http.Handler: one method, ServeHTTP(w, r). The programs on this page call handlers through httptest, so no port is opened.

  • A real program ends with http.ListenAndServe(":8080", handler), or better an http.Server with timeouts.
  • Each request runs in its own goroutine, so shared state needs a mutex.

ServeMux: method and path patterns

HTTP servers

Since Go 1.22 the built-in router matches "METHOD /path/{name}", and r.PathValue("name") reads the wildcard.

PatternMatches
GET /accounts/{id}one segment; GET also serves HEAD
/static/{path...}the rest of the path, slashes included
/static/everything under it (trailing slash means prefix)
/{$}exactly /; plain / matches every path

Interview point: the most specific pattern wins, whatever the registration order. Two patterns that overlap with neither more specific make HandleFunc panic at startup.

Reading query, headers and a JSON body

HTTP servers

Everything about the request is on *http.Request. There is no automatic validation as in FastAPI: decode, check, answer 4xx yourself.

  • Query().Get and Header.Get return "" when absent; convert with strconv.
  • The server closes r.Body for you. http.MaxBytesReader stops a client sending a huge body.

Status codes and JSON responses

HTTP servers

The order is fixed: headers, then WriteHeader(status), then the body. The first Write sends status 200 if you did not set one.

  • http.Error(w, msg, code) writes a plain-text error; it does not stop the handler, so return after it.
  • Use the constants: http.StatusCreated, http.StatusNotFound, http.StatusUnprocessableEntity.

Middleware: a function that wraps a handler

HTTP servers

Middleware is func(http.Handler) http.Handler, the same idea as a Python decorator. Code before next.ServeHTTP runs on the way in, code after it on the way out.

Each layer calls the next one, or answers and stops.
  • Embedding http.ResponseWriter in statusWriter is the standard way to capture the status code.
  • Put recovery outside auth and the handlers, logging outside everything.

Interview point: the server already recovers a handler panic and keeps running, but the client gets a dropped connection. Recovery middleware turns it into a clean 500.

Request context and cancellation

HTTP servers

r.Context() is cancelled when the client disconnects or the handler returns. Pass it to every database call and outgoing request so abandoned work stops.

  • Context itself is covered in Go concurrency: context.
  • For a per-request deadline: ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second).

Server timeouts and graceful shutdown

HTTP servers

http.ListenAndServe has no timeouts at all, so one slow client can hold a connection forever. Production code builds an http.Server.

Each timeout is the deadline for reaching the next box.

This program listens on port 0 (the OS picks a free one), calls itself once and shuts down.

Graceful shutdown: no new requests, running ones finish.
  • A service waits for signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) before Shutdown: see graceful shutdown.
  • WriteTimeout starts when the headers have been read, so it also caps handler time.
  • http.ErrServerClosed after Shutdown is the normal result, not a failure.

The accounts API: list, get, deposit

HTTP servers

The pieces together, as three files of one package main. httptest.NewServer starts it on a random local port and the program calls it like any client.

  • Handlers are methods on *API, so dependencies (store, logger, DB) are fields, not globals.
  • The mutex is needed because every request is a goroutine: see sync.Mutex.

HTTP clients and database/sql

Part 3 of 6 · calling other services and the database

http.Client with a timeout

HTTP clients and database/sql

http.Get uses http.DefaultClient, whose timeout is zero: it waits forever. Always build your own client.

Interview point: the zero-value client never times out, so one hung upstream ties up goroutines and connections until the service falls over. In Python terms: requests.get(url) without timeout=.

Request with context, status check, body, JSON

HTTP clients and database/sql

The full shape of one outgoing call. Unlike requests, there is no raise_for_status: a 404 or 500 is a normal response with err == nil.

Do returns after the headers; the body is still on the wire.

Connection reuse

  • Create one http.Client and share it: it is safe for concurrent use and its transport keeps a pool of keep-alive connections.
  • A connection goes back to the pool only when the body was read to the end and closed. Checked with net/http/httptrace: after closing a 1 MB body unread, the next request had to dial again.

Retries with backoff

HTTP clients and database/sql

Retry transport errors and 5xx, never 4xx, wait longer each time and stop when the context is done. The test server fails twice, then answers.

  • Retry only idempotent calls (GET, PUT, DELETE), or send an idempotency key with a POST.
  • Real code adds random jitter to the wait.

database/sql: DB is a pool, not a connection

HTTP clients and database/sql

The standard library has the API but ships no driver, so the SQL blocks in this part are compiled but not run. This one runs and shows what happens without a driver:

One DB per process; each query borrows a connection, a transaction keeps one.
  • Open once at startup and share the *sql.DB; it is safe for concurrent use. Never open per request.

Query, QueryRow, Exec and Scan

HTTP clients and database/sql

Three calls cover everything. Scan copies columns into pointers, in column order.

CallForRemember
QueryRowContextat most one rowno row: Scan returns sql.ErrNoRows
QueryContextmany rowsdefer rows.Close(), check rows.Err()
ExecContextINSERT, UPDATE, DELETERowsAffected()
sql.NullString, sql.Null[T]columns that can be NULLfields .V or .String, and .Valid

Interview point: always pass values as placeholders ($1 for PostgreSQL, ? for MySQL and SQLite), never with fmt.Sprintf: that is SQL injection. And a forgotten rows.Close() leaks a pooled connection.

Transactions with defer Rollback

HTTP clients and database/sql

A *sql.Tx holds one connection until Commit or Rollback. Deferring Rollback right away makes every early return safe.

  • Inside the transaction call methods on tx, not db: a db call uses another connection and runs outside the transaction.
  • Cancelling ctx rolls the transaction back.

Pool settings and context

HTTP clients and database/sql

Set the pool once after sql.Open. The defaults are no limit on open connections and two idle ones.

SettingDefaultMeaning
db.SetMaxOpenConns(25)0, unlimitedcap below the database's own limit; extra callers wait
db.SetMaxIdleConns(25)2connections kept ready; too low means constant re-dialling
db.SetConnMaxLifetime(5 * time.Minute)0, foreverrecycle so load balancers and failovers are picked up
db.SetConnMaxIdleTime(time.Minute)0, foreverclose connections idle this long
db.Stats()InUse, Idle, WaitCount: export these as metrics
  • Use the ...Context variants and pass r.Context(): a cancelled request cancels its query, or its wait for a free connection.

Files and I/O

Part 4 of 6 · os, bufio, io, filepath, embed

Read and write whole files

Files and I/O

os.ReadFile and os.WriteFile are the one-liners, like Path.read_bytes() and write_bytes() in pathlib. Appending needs os.OpenFile.

  • Test for a missing file with errors.Is(err, fs.ErrNotExist), not by reading the message.
  • 0o644 is the permission for a new file: owner writes, everyone reads.

Line by line with bufio.Scanner

Files and I/O

For input too large to load, or arriving as a stream, a Scanner gives one line per Scan(). It is the for line in f: of Go.

  • Check sc.Err() after the loop: Scan returns false both at the end and on an error.
  • A line over 64 KB stops the scan with bufio.ErrTooLong; raise the limit with sc.Buffer(buf, max).

Composing io.Reader and io.Writer

Files and I/O

Small wrappers plug together like pipes. Here one io.Copy prints the data, keeps a copy and hashes it, in a single pass.

TeeReader splits what is read, MultiWriter splits what is written.

Interview point: accept io.Reader or io.Writer in your own functions, not *os.File. The function then works on files, HTTP bodies and test strings alike.

defer Close and checking its error

Files and I/O

For a file you only read, defer f.Close() is enough. For a file you wrote, the error from Close matters, so return it through a named result.

  • defer is Go's with open(...) as f:. Place it right after the error check of the open call.
  • errors.Join returns nil when both errors are nil: see errors.Join.

Paths and temp files

Files and I/O

path/filepath is the pathlib of Go, as functions on strings. The output below is from macOS; Windows prints backslashes.

  • You remove MkdirTemp and CreateTemp results yourself.
  • In tests use t.TempDir(), which is deleted when the test ends.

embed: files inside the binary

Files and I/O

A //go:embed comment copies files into the executable at build time, so templates, migrations and static assets ship as one file. Python has no equivalent.

  • A folder: //go:embed static above var static embed.FS, then serve it with http.FileServerFS.
  • The directive must be directly above a package-level variable, and the package must import embed.

Everyday packages

Part 5 of 6 · time, strings, slices, slog, flag, os

time: Duration, formatting and parsing

Everyday packages

Go has no %Y-%m-%d. A layout is the reference time Mon Jan 2 15:04:05 MST 2006 written the way you want your time to look.

PieceLayoutPieceLayout
year2006hour (24, 12)15, 3 + PM
month01, Janminute, second04, 05
day02zoneZ07:00, MST

Interview point: the reference time is 1 2 3 4 5 6 7: month 1, day 2, hour 3 pm, minute 4, second 5, year 06, zone -07. Never write time.Sleep(5): that is 5 nanoseconds; write 5 * time.Second.

time: zones and timers

Everyday packages

A time.Time is an instant plus a location. Store and send UTC, convert with In(loc) only for display.

  • == also compares the location, so the same instant in two zones is not ==. Use Equal.
  • LoadLocation reads the system zone database; in a minimal container add import _ "time/tzdata".
  • Always Stop a ticker. For a timeout in a select, see timeouts.

strings, strconv, slices, maps and cmp

Everyday packages

String helpers are functions, conversions return an error where Python raises ValueError, and the generic helpers replace hand-written sort and search loops.

  • slices.SortFunc takes a three-way compare; cmp.Or returns the first non-zero result, which gives multi-key sorting.
  • Python's sorted(d) is slices.Sorted(maps.Keys(m)).
  • More in Go basics: the strings package, the slices package.

Structured logging with log/slog

Everyday packages

slog logs a message plus key-value pairs, as text or JSON. Python's logging formats strings; here the fields stay machine-readable.

The Logger is the front end; the Handler decides format, level and destination.
  • A real handler also writes a time field; dropTime removes it here to keep the output fixed.
  • Levels: Debug, Info, Warn, Error. Build one logger per request with With("request_id", id).

flag, environment and exit codes

Everyday packages

flag is a small argparse: typed flags with defaults and generated help. Each flag function returns a pointer that is filled by Parse.

  • Flags are -name value or -name=value, one dash or two. Parsing stops at the first non-flag argument.
  • No subcommands or required flags: check required values yourself after Parse.

Environment and exit codes

Keep main tiny: run() returns an error and main turns it into an exit status. This program exits 1 on purpose, so the session below shows a real build.

Interview point: os.Exit and log.Fatal skip deferred calls. Call them only in main, after run has returned and cleaned up.

errors, sync and context: already covered

Everyday packages

PackageIn one lineWhere
errorsWrap with fmt.Errorf("...: %w", err), test with errors.Is and errors.As.Go types: errors
syncMutex guards shared state, WaitGroup waits for goroutines, Once runs something one time.Go concurrency: sync
contextFirst parameter of anything that does I/O; carries cancellation and deadlines.Go concurrency: context

Testing

Part 6 of 6 · table tests, HTTP tests, benchmarks, fuzzing, and the cheat sheet

Table-driven tests, t.Helper and t.Cleanup

Testing

One slice of cases, one loop, one t.Run per case: Go's answer to pytest.mark.parametrize.

  • t.Errorf records a failure and continues; t.Fatalf stops that test.
  • Run one case with go test -run 'TestWithdraw/too_much' (spaces in names become underscores).

Testing HTTP handlers

Testing

Two levels: httptest.NewRecorder calls the handler as a function, httptest.NewServer runs a real server on loopback.

Left path: no network at all. Right path: the full HTTP stack.
  • The same NewServer is how you fake an upstream service when testing a client.

Benchmarks

Testing

A benchmark is func BenchmarkX(b *testing.B) with the measured code inside for b.Loop(). The numbers below are from one laptop and differ on every machine and run.

  • Columns: iterations, time per operation, bytes and allocations per operation (-benchmem).
  • -run '^$' skips the ordinary tests; -10 in the name is GOMAXPROCS.

Interview point: s += x in a loop copies the whole string every time, which is the 1000 allocations above. strings.Builder grows one buffer.

Fuzz tests

Testing

A fuzz test states a property and lets Go generate inputs to break it. The session output varies per run.

  • A failing input is saved under testdata/fuzz/ and replayed by every later go test, so it becomes a regression test.
  • Good targets: parsers, decoders, anything that takes bytes from outside.

Coverage and the race detector

Testing

Both are flags on go test, shown here on the bank package from table-driven tests. Timings vary.

  • go tool cover -html=cover.out opens the source in a browser with uncovered lines in red.
  • Run -race in CI on every push: it only reports races that actually happen during the run. Details: the race detector.

Cheat sheet: which package for what

Testing

NeedPackageStart with
JSONencoding/jsonMarshal, Unmarshal, NewDecoder
HTTP servernet/httpNewServeMux, HandleFunc, http.Server
HTTP clientnet/http&http.Client{Timeout: ...}, NewRequestWithContext
SQLdatabase/sql + a driversql.Open, QueryContext, BeginTx
Whole filesosReadFile, WriteFile, OpenFile
Lines, bufferingbufioNewScanner, NewWriter
Streamsio, bytesio.Copy, io.ReadAll, bytes.Buffer
Pathspath/filepathJoin, Base, WalkDir
Bundled filesembed//go:embed, embed.FS
Dates and durationstimeFormat, Parse, Duration
Textstrings, strconvCut, Fields, Builder, Atoi
Collectionsslices, maps, cmpSortFunc, Contains, maps.Keys
Logginglog/slogslog.New(slog.NewJSONHandler(...))
CLI and configflag, osflag.Int, os.Getenv, os.Exit
Teststesting, net/http/httptestt.Run, NewRecorder, b.Loop

That completes the Go track. Back to all Go tutorials.