Decode JSON Into Anonymous Structs
Decode one-off payloads with inline anonymous structs and json tags, including nested check lists, without declaring named types for every shape.
Page 6 of 8
Decode one-off payloads with inline anonymous structs and json tags, including nested check lists, without declaring named types for every shape.
Show that json.Marshal encodes []byte fields as base64 strings and Unmarshal decodes them back to the original bytes without manual encoding steps.
Hash JSON payloads deterministically by decoding into any and re-marshaling, so two payloads that differ only in map key order produce the same digest.
encoding/json matches keys exactly first and case-insensitively as a fallback, so apikey still fills APIKey; unmatched keys are dropped silently.
The ,string struct tag option encodes numeric fields as quoted JSON strings and decodes them back, enforcing quoted-number wire contracts on both sides.
errors.As distinguishes malformed JSON from type mismatches: json.SyntaxError reports the failing byte offset and UnmarshalTypeError names the target field.
Inspect arbitrary JSON without a target struct by walking Decoder.Token one step at a time, and use Decoder.More to advance through arrays.
json.Unmarshal silently ignores bytes after the first JSON value; pair json.Decoder with a second Decode to reject inputs that carry trailing data.
Unmarshal arbitrary JSON into map[string]any and flatten nested objects and arrays into dot-path keys with a recursive type-switch walk.
Cap untrusted JSON at a byte budget by reading through io.LimitReader with a one-byte probe, rejecting oversized payloads before json.Unmarshal sees them.
json.Marshal sorts map keys before encoding, so map output is byte-stable across runs, while struct fields keep declaration order instead.
Use the Go 1.24 omitzero tag to drop zero-valued time.Time structs and custom IsZero() fields — both cases omitempty keeps under its empty-value definition.
Mark fields with json:"-" so passwords and session tokens never enter encoded output, while staying fully usable inside the process.
Validate enum-like fields at decode time by implementing UnmarshalJSON, so unknown status values become decode errors instead of leaking into business logic.
Since Go 1.22 each loop iteration creates fresh variables, so closures and goroutines capture that iteration value instead of silently sharing one variable.
Parse raw To and From headers with net/mail ParseAddress and ParseAddressList, keeping the display name separate from the routed address.
Maps have no order, so copy entries into a slice and sort with SortFunc by value descending, using the key as a tiebreak for a stable ranked report.
Register subcommands in a map[string]func table so new commands need one line, lookups report missing keys, and unknown input falls back to help.
Invert a map into a reverse lookup and surface duplicate values as collisions, iterating keys in sorted order so the surviving key is deterministic.
Route string keys to shards with maphash: fast per-process hashing whose seed differs every run, so hashes are never persisted or shared across processes.
maps.Insert consumes an iter.Seq2 of key-value pairs straight into a map, overwriting existing keys, so loading data skips the collect-then-loop boilerplate.
maps.Keys hands back an iterator and slices.Sorted collects it into a sorted slice, so stable map output needs no manual key collection loop.
The method set of a value type only carries value receivers, so interfaces holding the pointer can call mutators that the plain value cannot reach.
Look up canonical MIME types by extension with mime.TypeByExtension: built-in table entries come back directly, unknown extensions return an empty string.
Clamp configuration values into a valid range with the min and max builtins, letting the helper survive swapped low and high bounds.
Measure elapsed time with time.Since so wall-clock adjustments never skew durations, and strip the monotonic reading with Round(0) before persisting.
io.MultiWriter forwards a single Write to every destination at once, so one call can update stdout and an in-memory audit buffer identically.
Embed sync.Mutex in a struct, call methods through pointer receivers, and join goroutines so multi-field state stays consistent and the lock is never copied.
Marshal a nil map as JSON null and an empty map as {}, and remember decoding null hands back a nil map while {} yields an initialized empty one.
Nil slices marshal to null, empty slices to []; both append and iterate identically, and omitempty drops either because a length-zero slice counts as empty.
Show which nil map operations are safe — len and comma-ok lookup — and which one panics on assignment, then allocate with make before writing.
Open log files with O_APPEND|O_CREATE so every write lands at the end without truncating, and see the O_TRUNC contrast for whole-file rewrites.
Replicate a whole directory tree with os.CopyFS over an fs.FS, then walk the destination to verify every file landed before cleanup removes the temp roots.
os.CreateTemp and os.MkdirTemp generate collision-free names, and deferred Remove calls keep scratch files from leaking between runs.
List one directory level with os.ReadDir, whose entries arrive sorted by name, then filter by extension and read each file size through DirEntry.Info.
os.Root scopes every lookup to one directory: paths that climb out with .. are rejected outright while normal reads and writes keep working.
Let one owner goroutine exclusively own a map and serve set and get requests over channels, the confinement idiom that replaces locks with message passing.
Preallocate one result slot per input so each goroutine writes only its own index: disjoint writes need no mutex and order matches the input slice.
Draw unique items with rand/v2 Perm indexing into the pool, then validate coverage by counting distinct winners across repeated seeded runs.
Reorder slices with rand v2 Shuffle: a seeded PCG rng reproduces the exact permutation across runs while the package-level call shuffles randomly.
Count loop iterations with for range over an integer, dropping the init-and-increment header, and reuse the index when you also need numbered slices.
reflect.DeepEqual compares maps, slices, and structs field by field, ignores map key order, and still reports NaN and func values as unequal.
Dispatch any values through reflect.TypeOf with a Kind switch, so named types resolve to their underlying kind and slices or maps expose elem and key kinds.
Named capture groups with ?P<name> pull structured fields out of log lines, and SubexpNames builds a name-to-value map without positional guessing.
Each query carries its own reply channel, so one worker goroutine owns the map exclusively and answers every caller without a mutex.
Implement a bounded history with a fixed slice, head and tail indexes, and modulo wrap-around, overwriting the oldest entries once capacity is reached.
Send every outgoing request through a custom RoundTripper that injects an Authorization Bearer header, cloning the request first so callers are never mutated.
runtime.GOMAXPROCS(0) reports the parallelism limit without changing it, and the same query sizes a worker pool instead of hard-coding a count.
A select with a default case turns channel sends and receives into non-blocking operations, dropping jobs when a bounded queue is already full.
A two-stage select drains the priority channel non-blocking first, then blocks on both channels, so urgent messages never wait behind bulk traffic.
Compute file digests by streaming bytes through sha256.New with io.Copy, and confirm the small-payload path with sha256.Sum256 on the same content.
Build a LIFO stack on a slice type: append to push, truncate to pop, and an ok return keeps empty-stack calls from ever indexing out of range.
slices.Chunk walks a slice in fixed-size batches through an iterator, yielding one shorter final batch when the length is not evenly divisible.
Build new slices with slices.Concat joining multiple sources and slices.Repeat tiling a pattern n times, leaving every input untouched.
Reserve capacity for upcoming appends with slices.Grow so bulk inserts stop reallocating, and compare against the repeatedly-growing baseline.
Reshape slices in place with slices.Insert, slices.Delete, and slices.Replace while watching len shift as elements move inside the backing array.
MinFunc and MaxFunc take a comparator and return the smallest or largest struct without a natural ordering, falling back to the zero value on empty slices.
Flip order in place with slices.Reverse and walk a slice from its last index with slices.Backward, which yields index and value together.
Give a slice Len, Less, and Swap methods to satisfy sort.Interface, then wrap it in sort.Reverse for descending order without rewriting the comparator.
Use slices.SortStableFunc when equal keys must keep their input order: unstable SortFunc may reorder records that compare the same.
Sscanf applies a format template to unstructured input, filling pointer arguments and returning the matched count plus an error instead of panicking.
Classify a path before use with os.Stat: distinguish missing files, directories, regular files, and errors through errors.Is and the mode bits.
Parse integers with ParseInt base 0 so 0x, 0o and 0b prefixes plus underscore separators pick their radix automatically and overflow surfaces as ErrRange.
Converting between string and []byte copies the data each way, so byte-slice edits never touch the original string, and len counts UTF-8 bytes not runes.
Apply per-rune transformations with strings.Map: replace characters, drop runes by returning negative values, and see the result stay a fresh string.
Iterate delimiters with strings.SplitSeq to stream substrings without materializing a slice, and keep strings.Split for indexed access.
Print aligned CLI tables with text/tabwriter: tab-separated cells line up in columns once Flush runs, with configurable padding and a chosen pad character.
Check service readiness with net.DialTimeout: dial with a bounded budget, close the descriptor immediately, and treat refusal and timeout as distinct outcomes.
Register helper functions on a FuncMap so templates call them through pipelines, keeping width padding and casing rules out of application code.
The three-index slice expression clamps cap so append allocates fresh backing arrays instead of silently overwriting elements of the parent slice.
time.Time.Compare returns a three-way result that sorts directly, while Before and After answer boolean questions; ties are resolved by service name.
Format and parse times through the reference-time layout Mon Jan 2, reusing constants like RFC3339 in both directions for lossless round trips.
Parse duration strings like 300ms and 1h30m with time.ParseDuration, seeing which units it accepts, how it renders 90s, and why a bare number fails.
time.Truncate rounds timestamps down to a fixed multiple, so raw event times collapse into stable hour buckets for counters and reports.
Give slow handlers a hard deadline with http.TimeoutHandler, which returns 503 with a custom message and throws away the late response entirely.
Reuse one time.Timer across select iterations by stopping, draining, and resetting it, so the idle timeout renews after every event without new allocations.
Reuse a single http.Transport and set MaxIdleConns, MaxIdleConnsPerHost, and IdleConnTimeout deliberately, because the per-host idle default is only 2.
An interface holding a nil pointer is not a nil interface: it still carries the concrete type, so == nil lies while method calls still dispatch.
Range over strings yields runes that unicode.IsLetter, IsDigit, and IsPunct classify, while strings.Map rewrites or drops each rune in one pass.
Track workers with the WaitGroup Go method added in Go 1.25, which starts each closure in a goroutine and joins it, replacing manual Add and Done calls.
Convert wg.Wait into a channel receive so select can race completion against a deadline, and see that timed-out workers keep running without one.
Coordinate lock-free handoff with atomic CompareAndSwap, where one goroutine wins the swap and concurrent counters retry until their write lands.
Stage writes in a same-directory temp file then os.Rename it over the target, so readers see the old or the new content and never a partial write.
A send to an unread unbuffered channel parks its goroutine forever — count them with runtime.NumGoroutine and cap the channel to let senders finish.
Struct fields marshal in declaration order while map keys always come out sorted, so reproducible payloads and hashes choose their carrier deliberately.
Decode optional fields into pointer types so missing or null JSON reads as nil instead of the zero value, with omitempty dropping nil fields on marshal.
Carry timestamps in encoding/json through time.Time fields, which parse and emit RFC3339 strings automatically, with time.Parse validating raw stamps.
Check payloads with json.Valid, strip whitespace with Compact, and re-indent with Indent — shaping raw JSON without building a decode tree.
Delete map entries during range safely — Go skips removed entries instead of crashing — and delete() on a missing key is a documented no-op.
Collect slice rows into map[string][]T buckets keyed by a field, then sort the keys so grouped output stays stable across runs.
Compare map key sets with intersect and difference helpers, then sort results since map iteration order is randomized on every run.
Use comparable structs and fixed-size arrays as map keys so composite coordinates collapse to one entry, while slice keys are a compile-time error.
Merge several channels and set drained ones to nil so their select cases stop firing, letting the fan-in loop finish instead of spinning on zero values.
Test membership and equality with slices.Contains, ContainsFunc, IndexFunc, and EqualFunc so lookups and comparisons stay declarative.
Locate the first qualifying position with sort.SearchInts and the predicate-based sort.Search, handling the all-true and all-false boundaries yourself.
Load named zones with LoadLocation, pin offset-less wall clocks with ParseInLocation, and convert the same instant across UTC and other zones.
Show an unbuffered channel blocking the sender until the receiver is ready, while a buffered channel absorbs sends up to capacity without anyone waiting.
Parse a URL into components, mutate the query with url.Values Add, Set, and Del, then re-encode it — with QueryEscape for free-form text values.
Range over strings knowing indexes are byte offsets, count runes instead of bytes, and cut safely with ValidString guarding mid-rune slices.
Close a channel after the last send so range loops end naturally and later receives return the zero value with ok false instead of blocking forever.