Fan-Out and Fan-In Pipeline in Go
Split work across fixed goroutines, merge every output through a fan-in channel, and restore the original input order in the result slice.
Page 45 of 50
Split work across fixed goroutines, merge every output through a fan-in channel, and restore the original input order in the result slice.
Flip a readiness probe before shutdown, wait for load balancers to stop routing, then drain in-flight HTTP requests with a bounded timeout.
Drain in-flight HTTP requests on SIGINT or SIGTERM with http.Server.Shutdown, a bounded grace period, and a clean Serve error check.
Compress HTTP responses when the client advertises gzip support, set Vary correctly, and skip negotiation for other clients.
Render untrusted names, bodies, and links through html/template so contextual escaping blocks script injection and bad URLs.
Cap JSON request bodies with MaxBytesReader, reject oversized payloads with 413, and reuse the middleware across handlers.
Format byte counts with binary units and parse human-readable sizes back into integers with rounding and unit validation.
Encode a large result set incrementally with json.Encoder and a buffered writer instead of marshalling the whole slice at once.
Resolve RFC 6901 JSON pointers against decoded documents, with strict escape validation and clear traversal errors.
Decode newline-delimited JSON events one at a time with json.Decoder, validate each record, and aggregate without buffering the file.
Encode keyset cursors as opaque base64 JSON and page records by creation time and ID without offset drift.
Compare two slices of text lines with a longest common subsequence table and emit stable add, remove, and equal operations.
Combine a map with a doubly linked list to evict least-recently-used entries and expire stale keys on read and write.
Compose request ID, structured logging, and panic recovery middleware in Go while preserving the original handler order.
Bucket observations into a fixed histogram and estimate p50, p90, and p99 without keeping every sample in memory.
Fan out events to multiple subscribers with buffered channels, dropping events for slow consumers instead of blocking publishers.
Validate or generate a request ID, echo it in the response header, and expose it through a private context key for logging.
Retry transient operations with capped exponential delays, full jitter, context cancellation, and a permanent-error sentinel.
Share one in-flight load across concurrent callers, report who led the work, and prevent a cache stampede after expiry.
Remove duplicate comparable values while preserving first-seen order, returning a new slice so the caller's data stays untouched.
Serve a built frontend from disk, fall back to index.html for extensionless routes, and return 404 for missing assets.
Map nullable database columns into sql.NullString and *string fields, then emit clean nulls through a custom JSON view.
Cut per-request allocations by borrowing bytes.Buffer from sync.Pool, copying the encoded JSON, and always returning the buffer.
Write table-driven Go tests that use subtests, parallel execution, and a shared example for email normalization cases.
Store strings in a rune-aware trie, check exact prefixes, and collect completions in sorted order with a depth-first walk.
Wrap database work in a transaction helper that rolls back on error and retries serialization conflicts with short backoff.
Store request-scoped values in context.Context with generic key types so lookups are type-safe and cannot collide by string.
Bound the total weight of concurrent work, acquire and release arbitrary weights, and wake waiters when capacity frees up.
Build a bounded Go worker pool that fans jobs out to fixed workers, streams results, and stops promptly on context cancellation.
Schedule jobs by priority with a bounded worker pool, keep FIFO order for equal priorities, and stream results through one channel.
Walk a directory into a zip file while rejecting entries that escape the root, preserving relative paths with forward slashes.
Write and compare golden files with trailing whitespace tolerance, producing a compact line diff when output drifts.
Compute great-circle distance in kilometers between coordinates and build a latitude and longitude bounding box for prefiltering.
Serve a single file from a confined root and rely on ServeContent for partial content, conditional requests, and range headers.
Spin up an in-process stub server with canned JSON responses, track request counts atomically, and exercise not-found paths.
Maintain a running median in logarithmic time using a max-heap for the lower half and a min-heap for the upper half.
Implement 32-bit Murmur3 and map keys to stable shards, with a distribution check over ten thousand sample keys.
Forward requests with httputil.ReverseProxy, add a forwarded-host header, strip internal headers, and return 502 on failure.
Reduce lock contention with a fixed set of independently locked shards, safe for concurrent writes from many goroutines.
Track request timestamps in a sliding window to enforce a precise per-interval quota, with an injectable clock for tests.
Broadcast events to browser clients over text/event-stream with per-client buffers, dropped slow consumers, and flush calls.
Run a child process under a context deadline, capture stdout and stderr together, and report a clear timeout error.
Pick items with arbitrary positive weights using one random draw, rejecting bad weights and checking the distribution.
Decode YAML into typed structs with unknown-field rejection, then validate required addresses, durations, and size limits.
Build a native HTML modal with showModal, labelled and described content, Escape and backdrop dismissal, and a live result message.
Style a native multiple file input with a focusable label button, announce selected files, and reject oversized files before upload.
Validate a signup form with a focusable error summary, linked error messages, aria-invalid states, and a polite success announcement.
Sort an HTML data table with real buttons, keep aria-sort on the active column, and announce each sort change to screen readers.
Run a batch on a fixed thread pool with invokeAll and a deadline, inspect completed futures, and shut the executor down cleanly.
Validate and normalize a Java record in its compact constructor, default missing display names, and defensively copy a role list.
Aggregate sales with Collectors groupingBy, TreeMap ordering, and teeing to compute count and average in one pass over a Java stream.
See how Java closes resources in reverse order and attaches a failing close to the primary exception as a suppressed throwable.
Parse Accept headers with q-values and wildcards, then pick the best supported media type while honoring q=0 exclusions and server order.
Compute exact years, months and days between a birth date and a reference date using UTC date-only arithmetic.
Split arrays or any iterable into fixed-size chunks with strict size validation, ordered output and a lazy generator variant.
Combine parallel arrays into tuples and split a collection by predicate, with a zipLongest variant that pads short inputs.
Serialize critical sections with an async mutex that queues waiters in FIFO order, supports acquisition timeouts and safe double release.
Check whether parentheses, square brackets and braces are balanced and correctly nested with a single-pass stack algorithm.
Encode UTF-8 text with the RFC 4648 Base32 alphabet, add correct padding, and decode back while rejecting invalid characters.
Encode strings or bytes to unpadded base64url and decode back with strict alphabet, length and fatal UTF-8 validation.
Find the first and last insertion points for a value in a sorted array with a custom comparator, then count duplicates in logarithmic time.
Represent up to 30 permissions as one 32-bit mask with helpers to build, test, add, remove, toggle and list enabled flags.
Find a strict majority element in linear time and constant space, plus a generalized Misra-Gries pass for multiple frequent values.
Append a stable version or content-hash query parameter to asset URLs without losing existing params or fragments.
Shift ASCII letters by any integer offset with alphabet wrapping, and expose ROT13 as a fixed thirteen-position special case.
Convert identifiers between camelCase, snake_case and kebab-case with word-boundary splitting, input validation and predictable output.
A cooperative cancellation primitive with reasons, unsubscribe callbacks, throwIfCancelled and linked token sources that cascade cancellation.
Parse MM/YY card expiry values, compare them against an injectable clock and report whether the card is valid through month end.
Format large counts as 1.2K or 3.4M with Intl.NumberFormat compact notation and configurable locale and precision.
Map over an array with a fixed concurrency limit, preserve result order, propagate the first error, and honor an AbortSignal.
Compare secrets without early exit by XOR-ing UTF-8 bytes, reducing timing leaks in token and signature checks.
Parse attachment and inline headers, including RFC 5987 filename*, while stripping directory components from untrusted names.
Parse a Cookie request header into a null-prototype object, handling quoted values, duplicates and RFC 6265 rules.
Serialize browser cookies with Max-Age, Expires, Path, Domain, Secure, HttpOnly and SameSite, plus a tolerant Cookie header parser.
Parse one CSV row with a configurable delimiter, quoted fields, doubled quotes and strict errors for malformed input.
Incrementally parse CSV chunks with quoted fields, escaped quotes, embedded newlines, and CRLF endings using a dependency-free state machine.
Transform multi-argument functions into curried variants that support placeholders and partial application.
Recursively freeze arrays and objects while tolerating cycles, accessors and typed arrays that cannot be frozen with elements.
Merge nested configuration objects without mutation, cloning arrays and special values while blocking prototype-pollution keys.
A growable ring-buffer deque with amortized O(1) pushes and pops at both ends, plus indexed snapshot access.
Normalize local and international phone input into E.164 format with country dial codes, trunk-prefix handling and length checks.
Mask the local part of email addresses while preserving the domain, with short-address handling and an option to hide subdomains.
Parse entity-tag lists and evaluate If-Match and If-None-Match with the strong or weak comparison rules required by HTTP caching.
A small event emitter that adds one-shot listeners, removal by original callback, snapshot dispatch and listener counts without Node dependencies.
Shuffle arrays in place or on a copy using crypto-backed rejection sampling to avoid modulo bias and preserve uniform permutations.
Flatten arbitrarily nested arrays with an explicit stack and optional depth limit, avoiding call-stack overflow on deep input.
Turn raw byte counts into readable IEC or SI strings with configurable decimals, spacing and correct handling of zero and negatives.
Group array items by a computed key or property name into a Map that preserves first-seen key order and supports value projection.
Build a max heap and sort an array in place in O(n log n) time with no extra allocations, using a pluggable comparator for custom orders.
Parse three- and six-digit hex colors into RGB channels and convert validated RGB objects back to lowercase hex strings.
Validate DNS hostnames label by label, enforcing length limits, allowed characters, hyphen placement and an optional root dot.
Escape ampersands, angle brackets, quotes and newlines before inserting untrusted values into HTML or attributes.
Generate Cache-Control and ETag headers, then evaluate If-None-Match and If-Modified-Since to return 304 or 200 responses correctly.
Format Dates as IMF-fixdate for HTTP headers and parse all three legacy HTTP date formats into Date objects.
Classify HTTP status codes by class and expose retryable, cacheable, success and error flags for client logic.
Convert milliseconds into compact durations such as 1h 5m 20s with unit limits, short labels and zero handling.
Parse INI configuration into null-prototype objects with sections, comments, quoted values, type coercion and duplicate detection.
Parse dotted-quad IPv4 addresses strictly, reject leading zeros, and classify private, loopback and link-local ranges.
Calculate ISO 8601 week numbers and convert a year plus week back to the Monday that starts it, with round-trip validation.
Write newline-delimited JSON logs with levels, child context, timestamps, and safe serialization of errors, circular data, and BigInt.