Standard library & project layout
26 steps in 8 sets of Go.
Go's standard library is unusually complete, and this tour is a working tour of it. Encoding, time, files and IO, collections and text, program structure and logging, HTTP, then packages and the build system.
Twenty-six steps. The net/http server in here is production-grade, which is not something most languages can say about their standard library.
Encoding
- JSON encodingStruct tags map Go fields to JSON keys.
- JSON in and outMarshal and Unmarshal, with tags deciding the wire names.
- Streaming JSONDecoder and Encoder work over a reader and a writer, one value at a time.
Time
- Formatting timeGo's layout is an example time, not percent codes.
- DurationsA Duration is a count of nanoseconds with units in the literal.
Files & IO
- Reading linesbufio.Scanner walks a reader line by line, and its error needs checking.
- FilesRead a whole file, write one, or open it and defer the close.
- Paths and walkingfilepath joins with the right separator and walks a tree.
Collections & text
- The slices packageGeneric helpers that used to be hand-written in every project.
- The maps packageIterating a map's keys and values without writing the loop.
- SortingOrdering slices with a custom less function.
- strconvText to number and back, with the error you must handle.
- Regular expressionsCompile once, reuse; named groups make the match readable.
Programs & logging
- Command-line flagsThe flag package declares, parses and documents the interface.
- Structured logginglog/slog writes key-value pairs, at a level, in text or JSON.
HTTP
- Routing with the standard muxGo 1.22 taught ServeMux methods and path variables.
- An HTTP handlerServing JSON with net/http and ServeMux.
- MiddlewareA middleware takes a handler and returns one that wraps it.
- An HTTP clientFetching and decoding JSON with a timeout.
- An HTTP client that gives upA shared client with a timeout, and a request carrying a context.
Packages & build
- Package documentationA comment directly above the package clause documents the package.
- Struct tagsA tag is metadata on a field, read by reflection at run time.
- Build constraintsA //go:build line decides whether the file is compiled at all.
- Embedding filesgo:embed puts files into the binary at compile time.
- go:generateA comment that records the command which regenerates a file.
Encore
- serve_json.goA JSON API with the standard mux: routes, middleware, graceful shutdown.