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
Only exported fields take part. The tag json:"name" sets the key, json:"-" hides a field.
- 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
Options after the key name decide when a field is left out.
| Option | Drops the field when |
|---|---|
omitempty | false, 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
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
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
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.
MarshalJSONon the value receiver,UnmarshalJSONon the pointer receiver (it must modify the value).- Never call
json.Marshal(r)on the same type inside its ownMarshalJSON: that recurses forever. Convert to a plain type first.
time.Time in 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.Timein 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
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.
Encodeadds a newline after each value;Marshaldoes 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
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 anhttp.Serverwith timeouts. - Each request runs in its own goroutine, so shared state needs a mutex.
ServeMux: method and path patterns
Since Go 1.22 the built-in router matches "METHOD /path/{name}", and r.PathValue("name") reads the wildcard.
| Pattern | Matches |
|---|---|
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
Everything about the request is on *http.Request. There is no automatic validation as in FastAPI: decode, check, answer 4xx yourself.
Query().GetandHeader.Getreturn""when absent; convert withstrconv.- The server closes
r.Bodyfor you.http.MaxBytesReaderstops a client sending a huge body.
Status codes and JSON responses
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, soreturnafter it.- Use the constants:
http.StatusCreated,http.StatusNotFound,http.StatusUnprocessableEntity.
Middleware: a function that wraps a handler
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.
- Embedding
http.ResponseWriterinstatusWriteris 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
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.ListenAndServe has no timeouts at all, so one slow client can hold a connection forever. Production code builds an http.Server.
This program listens on port 0 (the OS picks a free one), calls itself once and shuts down.
- A service waits for
signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)beforeShutdown: see graceful shutdown. WriteTimeoutstarts when the headers have been read, so it also caps handler time.http.ErrServerClosedafterShutdownis the normal result, not a failure.
The accounts API: list, get, deposit
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.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
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.
Connection reuse
- Create one
http.Clientand 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
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
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:
- Open once at startup and share the
*sql.DB; it is safe for concurrent use. Never open per request.
Query, QueryRow, Exec and Scan
Three calls cover everything. Scan copies columns into pointers, in column order.
| Call | For | Remember |
|---|---|---|
QueryRowContext | at most one row | no row: Scan returns sql.ErrNoRows |
QueryContext | many rows | defer rows.Close(), check rows.Err() |
ExecContext | INSERT, UPDATE, DELETE | RowsAffected() |
sql.NullString, sql.Null[T] | columns that can be NULL | fields .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
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, notdb: adbcall uses another connection and runs outside the transaction. - Cancelling
ctxrolls the transaction back.
Pool settings and context
Set the pool once after sql.Open. The defaults are no limit on open connections and two idle ones.
| Setting | Default | Meaning |
|---|---|---|
db.SetMaxOpenConns(25) | 0, unlimited | cap below the database's own limit; extra callers wait |
db.SetMaxIdleConns(25) | 2 | connections kept ready; too low means constant re-dialling |
db.SetConnMaxLifetime(5 * time.Minute) | 0, forever | recycle so load balancers and failovers are picked up |
db.SetConnMaxIdleTime(time.Minute) | 0, forever | close connections idle this long |
db.Stats() | InUse, Idle, WaitCount: export these as metrics |
- Use the
...Contextvariants and passr.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
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. 0o644is the permission for a new file: owner writes, everyone reads.
Line by line with bufio.Scanner
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:Scanreturns false both at the end and on an error. - A line over 64 KB stops the scan with
bufio.ErrTooLong; raise the limit withsc.Buffer(buf, max).
Composing io.Reader and io.Writer
Small wrappers plug together like pipes. Here one io.Copy prints the data, keeps a copy and hashes it, in a single pass.
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
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.
deferis Go'swith open(...) as f:. Place it right after the error check of the open call.errors.Joinreturns nil when both errors are nil: see errors.Join.
Paths and temp files
path/filepath is the pathlib of Go, as functions on strings. The output below is from macOS; Windows prints backslashes.
- You remove
MkdirTempandCreateTempresults yourself. - In tests use
t.TempDir(), which is deleted when the test ends.
embed: files inside the binary
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 staticabovevar static embed.FS, then serve it withhttp.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
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.
| Piece | Layout | Piece | Layout |
|---|---|---|---|
| year | 2006 | hour (24, 12) | 15, 3 + PM |
| month | 01, Jan | minute, second | 04, 05 |
| day | 02 | zone | Z07: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
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==. UseEqual.LoadLocationreads the system zone database; in a minimal container addimport _ "time/tzdata".- Always
Stopa ticker. For a timeout in aselect, see timeouts.
strings, strconv, slices, maps and cmp
String helpers are functions, conversions return an error where Python raises ValueError, and the generic helpers replace hand-written sort and search loops.
slices.SortFunctakes a three-way compare;cmp.Orreturns the first non-zero result, which gives multi-key sorting.- Python's
sorted(d)isslices.Sorted(maps.Keys(m)). - More in Go basics: the strings package, the slices package.
Structured logging with log/slog
slog logs a message plus key-value pairs, as text or JSON. Python's logging formats strings; here the fields stay machine-readable.
- A real handler also writes a
timefield;dropTimeremoves 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
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 valueor-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
| Package | In one line | Where |
|---|---|---|
errors | Wrap with fmt.Errorf("...: %w", err), test with errors.Is and errors.As. | Go types: errors |
sync | Mutex guards shared state, WaitGroup waits for goroutines, Once runs something one time. | Go concurrency: sync |
context | First 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
One slice of cases, one loop, one t.Run per case: Go's answer to pytest.mark.parametrize.
t.Errorfrecords a failure and continues;t.Fatalfstops that test.- Run one case with
go test -run 'TestWithdraw/too_much'(spaces in names become underscores).
Testing HTTP handlers
Two levels: httptest.NewRecorder calls the handler as a function, httptest.NewServer runs a real server on loopback.
- The same
NewServeris how you fake an upstream service when testing a client.
Benchmarks
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;-10in 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
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 latergo test, so it becomes a regression test. - Good targets: parsers, decoders, anything that takes bytes from outside.
Coverage and the race detector
Both are flags on go test, shown here on the bank package from table-driven tests. Timings vary.
go tool cover -html=cover.outopens the source in a browser with uncovered lines in red.- Run
-racein CI on every push: it only reports races that actually happen during the run. Details: the race detector.
Cheat sheet: which package for what
| Need | Package | Start with |
|---|---|---|
| JSON | encoding/json | Marshal, Unmarshal, NewDecoder |
| HTTP server | net/http | NewServeMux, HandleFunc, http.Server |
| HTTP client | net/http | &http.Client{Timeout: ...}, NewRequestWithContext |
| SQL | database/sql + a driver | sql.Open, QueryContext, BeginTx |
| Whole files | os | ReadFile, WriteFile, OpenFile |
| Lines, buffering | bufio | NewScanner, NewWriter |
| Streams | io, bytes | io.Copy, io.ReadAll, bytes.Buffer |
| Paths | path/filepath | Join, Base, WalkDir |
| Bundled files | embed | //go:embed, embed.FS |
| Dates and durations | time | Format, Parse, Duration |
| Text | strings, strconv | Cut, Fields, Builder, Atoi |
| Collections | slices, maps, cmp | SortFunc, Contains, maps.Keys |
| Logging | log/slog | slog.New(slog.NewJSONHandler(...)) |
| CLI and config | flag, os | flag.Int, os.Getenv, os.Exit |
| Tests | testing, net/http/httptest | t.Run, NewRecorder, b.Loop |
That completes the Go track. Back to all Go tutorials.