Relative Paths With filepath.Rel
Turn absolute targets into root-relative paths with filepath.Rel for reports and allowlist checks, expecting the leading .. when a target escapes the root.
Page 2 of 8
Turn absolute targets into root-relative paths with filepath.Rel for reports and allowlist checks, expecting the leading .. when a target escapes the root.
Count runes with a map, then rescan for the first rune whose count is one, returning its byte index so the winner can be sliced out of the string.
Durations parse with flag.Duration while TextVar routes richer types like netip.Addr through encoding.TextUnmarshaler, so bad text aborts the run early.
Distinguish user-set flags from declared defaults with flag.Visit and VisitAll, so help output only shows what was actually passed.
format.Source reformats complete Go snippets with the same rules as gofmt and returns a parse error instead of panicking on broken syntax.
Validate path shape with fs.ValidPath before any fs.FS read, rejecting absolute paths, dot segments, and empty elements at the gate.
Wrap any cmp.Ordered type in a container/heap min-heap with the five heap.Interface methods, so pop always yields the smallest value.
Copy unread response bodies to io.Discard before Close so keep-alive connections return to the pool and subsequent requests reuse them.
ParseForm decodes an application/x-www-form-urlencoded body so repeated keys become string slices and Form.Get returns the first submitted value.
StripPrefix removes a fixed path prefix before a FileServer, so static assets live under one URL subtree without moving files on disk.
Insert a comma every three digits by walking the formatted bytes, so reports read 1,234,567 without pulling in any formatting library.
io.NopCloser satisfies io.ReadCloser for a bare io.Reader; Close is a no-op and the underlying reader keeps its position after reads.
strconv.Itoa renders decimal digits while string(n) treats the integer as a Unicode code point, so the two are rarely interchangeable.
After decoding the first JSON value, Decoder.Buffered hands back everything left unread so another consumer can take over.
Each json.Encoder.Encode call appends a newline, so looping over records writes one compact JSON object per line that readers can parse row by row.
Show that json.Encoder.Encode appends a trailing newline while json.Marshal does not, so hashing, diffing, and bytes.Equal checks diverge.
Decode MaxInt64+1 into an int64 field to get UnmarshalTypeError, while the uint64 field beside it accepts the same number.
encoding/json detects reference cycles while marshaling and returns an unsupported-value error, so flat DTOs keep nested graphs serializable.
json.Marshal fails with an unsupported value error for NaN and Inf floats, so sensor-style readings must be filtered or sanitized before encoding.
encoding/json silently drops unexported struct fields, and the json:"-" tag excludes exported ones from both marshal and unmarshal roundtrips.
Decode custom string fields through UnmarshalText so one method owns trimming, parsing, and rejecting invalid duration syntax.
Sweep a slice once with Kadane: reset the running sum when it turns negative, track the best window, and print both the sum and the winning subarray.
Walk the first word column by column and compare against every other word, returning the longest common prefix as soon as any column diverges or ends.
Load numbers into a set and only count runs at their start (x-1 missing), so each element is visited at most twice and stays O(n).
The Luhn checksum doubles every second digit from the right, folds two-digit products, and accepts the number only when the total divides by ten.
make(map[K]V, n) preallocates room for n entries so bulk inserts skip repeated rehash growth, and maps.Copy into a sized map gets the same hint.
append returns a new slice header, so map values must be written back; a dropped append never shows up in the map regardless of spare capacity.
Build a fresh map from a filtered iter.Seq2 with maps.Collect while the source map stays untouched throughout the rebuild.
Walk the old map for removals and value changes, the new map for additions, then sort the key slices so diff reports stay reproducible.
Copysign takes the magnitude of one float and the sign bit of another, while Signbit reports the sign directly, so -0.0 is detectable as signed.
Rebuild a matrix with rows and columns exchanged through nested loops over a fresh [][]int, keeping the source untouched for shape-aware transformations.
Keep one head element per slice in a min-heap and always pop the smallest, so k sorted slices merge in one pass without re-scanning.
A second stack records each new minimum as it is pushed and pops it back off with the main stack, keeping the current minimum one read away.
Compact non-zero values to the front with two indexes that swap in place, pushing every zero to the back while preserving the relative order of values.
SplitHostPort separates host and port with required brackets for IPv6 literals, and JoinHostPort adds them back when joining either address family.
new(T) allocates a zeroed value and returns a pointer to any type, while make builds ready-to-use slices, maps, and channels only.
sync.OnceFunc replays the same panic value on every call after setup fails, unlike Once.Do where a panicking init is skipped as done.
Wrap a producer channel with orDone so a downstream consumer can cancel mid-stream while the wrapper and the producer both exit instead of leaking.
os.Pipe creates a kernel-level pipe of *os.File descriptors: a writer goroutine closes the write end so the Scanner reader reaches EOF cleanly.
Guard integer addition and multiplication against wraparound with range checks and divide-back verification so bad inputs fail loudly.
Multiple init functions in one file execute top to bottom after imports load, so config setup and connection warming finish before main starts.
Check palindromes by converging two indexes over a rune slice, so multibyte text like CJK phrases is compared per character instead of per byte.
Give each map key its own sync.Once guarded by one mutex, so expensive per-key setup runs exactly once even when many goroutines race the same key.
& takes an address, * reads or writes through it, and a nil pointer must be checked before dereferencing or the program panics at runtime.
Precompute a prefix slice so any sub-range sum becomes two index lookups, turning repeated O(n) scans into constant-time queries.
A custom io.Reader wraps another reader and rewrites each filled buffer in place, passing byte counts and EOF straight through so ReadAll composes.
Redact and mask each match through a ReplaceAllStringFunc callback, since replacement templates cannot run per-match logic like length-based masking.
Run-length encoding appends each run's count after its byte, and decoding rebuilds the original text only when every count was written back.
Stop a single worker with runtime.Goexit: deferred calls still run, siblings keep going, and the group reports which workers finished versus bailed out.
Yield the processor between appends with runtime.Gosched under GOMAXPROCS(1), so two goroutines visibly alternate and the recorded order proves each handoff.
Wrap any handler with middleware that injects nosniff, frame-deny, referrer and CSP headers so every response ships the same baseline defenses.
Both sides stay ready throughout the loop, so select picks a case by uniform pseudo-random choice and the win counts vary across runs.
Receiving from a closed channel stays safe and drains buffered values before zero-and-false, while a send panics until recover catches it.
A reserved sentinel job value makes a worker exit early, and closing the jobs channel stops the remaining workers waiting on receive.
Cancel out duplicate values with a single xor accumulator: identical pairs annihilate, leaving the one number that appears exactly once in the slice.
Extend an existing slice from an iter.Seq with slices.AppendSeq, appending into the same backing storage instead of allocating.
Watch slices.Delete shift elements left and zero the stale tail since Go 1.22, so old references into the backing array cannot leak data.
Compare slices for equality with slices.Equal and swap in a per-pair predicate via EqualFunc for case-insensitive matches.
Rotate slice elements left in place with slices.Rotate: no new backing array, wraparound at the end, and composable repeated shifts.
Convert slices to iter.Seq with slices.Values and rebuild with slices.Collect, so consumers can accept any iterator without caring about storage.
Track window maximums with a monotonic deque of indexes whose values stay decreasing, so each position pops outdated candidates and reads the front.
http.StatusText turns numeric status codes into canonical reason phrases and returns an empty string for unregistered codes like 599.
Append numbers into one reusable byte buffer with strconv.AppendInt and AppendQuote, truncating with buf[:0] between rounds instead of allocating new strings.
Reversing bytes scrambles multi-byte runes into invalid UTF-8, so reversal has to walk []rune pairs from both ends to keep text intact.
Compare auth scheme names with strings.EqualFold so Bearer, BEARER and bearer all route correctly; credentials themselves need a constant-time compare.
Marshal a struct and unmarshal it into map[string]any to add or delete keys dynamically, then remarshal with keys in sorted order.
Pipe data through a subprocess with StdinPipe and StdoutPipe: write lines to the child, stream its sorted output back with a Scanner, then Wait for exit.
A supervisor loop respawns a worker goroutine after each recovered panic, stops once the worker completes, and gives up after a fixed attempt budget.
A panic inside sync.Once.Do still marks the Once done, so later calls skip the init and a failed initialization is never retried.
Load text templates through template.ParseFS from any fs.FS source, so tests can use fstest.MapFS while production swaps in embed.FS untouched.
Example functions run under go test with their // Output: comment compared verbatim, keeping documentation snippets honest as the code evolves.
t.Parallel marks subtests to pause and run concurrently after serial setup, while copying each case into the closure keeps shared loop state per-test.
Show that time.Duration(1500) means 1500 nanoseconds, not milliseconds: untyped integer conversions silently shrink durations by three orders of magnitude.
Compare times with Equal and Compare: the eq operator fails across locations and after Round strips the monotonic clock reading.
Try a prioritized list of layouts with time.Parse and wrap the last error, so timestamps arriving from different systems parse with one entry point.
Walk two pointers inward tracking the tallest wall on each side; water above a column is bounded by the shorter of the two maxima.
Two indices walking inward from both ends of a sorted slice locate a pair summing to the target in one pass, discarding one impossible element per step.
Build a FIFO queue from two stacks so each element moves at most twice: push appends to the inbox stack, pop reverses it once into the outbox stack.
Convert between string and []byte without copying via unsafe.String and unsafe.StringData, and state the read-only contract that keeps it safe.
Parse query strings with url.ParseQuery and surface malformed input: bare semicolons and invalid percent escapes return errors instead of dirty data.
Run sequential batches of goroutines with one WaitGroup: after each Wait the counter is back at zero, so the same group serves the next phase.
Each WaitGroup worker writes its result into a fixed slot, and errors.Join merges the non-nil errors into one value after all goroutines finish.
Greedy wrapping breaks text into lines no wider than the limit, splitting only at spaces and pushing an overlong word to its own line.
Generate an ECDSA key, issue a self-signed certificate with CreateCertificate, parse the DER back with ParseCertificate, and encode it as PEM.
Stream XML incrementally with xml.Decoder.Token: start elements, character data, and end elements arrive as you ask, without loading the whole tree.
Build lock-free state flags on atomic.Uint32 with bit masks and CompareAndSwap, so a busy bit flips only when the current word still matches.
The same bytes encode differently under base64.StdEncoding and base64.URLEncoding: +/ become -_ in the URL alphabet, and Raw variants drop = padding.
Extend 64-bit arithmetic with math/bits.Add64 and bits.Mul64, which surface carries and high halves so multi-word sums and products stay exact.
bufio.ScanWords streams whitespace-separated tokens from any reader, so word counting works incrementally without loading whole input.
copy moves min(len(dst), len(src)) elements and returns that count, so short destinations silently truncate and you can detect it.
SignASN1 produces a DER-encoded ECDSA signature over a SHA-256 digest, and VerifyASN1 rejects the same signature for a different message.
Assemble RFC 4122 version-4 UUIDs from crypto/rand bytes by setting the version and variant bits, then format canonical hex groups.
csv.Reader with FieldsPerRecord set to -1 accepts rows of any width, while the default mode rejects records that differ from the first row.
debug.ReadBuildInfo reports the module path, Go version, and VCS revision so a CLI binary can print its own version information.
Deferred call arguments are evaluated when the defer statement runs, while a deferred closure reads the variable's latest value.
fmt.Fscan pulls whitespace-separated tokens from any reader and converts them by pointer type, so parsing does not need a fixed layout.
SetBasicAuth writes the standard Authorization header for you: base64 of user:password that decodes back with a single colon separator.
Comparing two interface values whose dynamic type is a slice or map panics at runtime; guard the comparison with recover or a type switch.
Write an iter.Seq2 function yielding line-number and text pairs so range-over-func consumers can break out and stop the iterator.
Decode a JSON array of records, sort by a numeric field with slices.SortFunc, then re-encode so reports stop trusting upstream ordering.