Binary Search Variant With Lower Bound (Go)
Find the leftmost position where a sorted slice can accept a target using a Go binary search lower bound variant.
Find the leftmost position where a sorted slice can accept a target using a Go binary search lower bound variant.
Generate a Gray code sequence of n bits in Go using bit manipulation where consecutive values differ by one bit.
Implement a Go bloom filter with k hash functions for probabilistic membership testing.
Implement a Go binary search tree supporting insert and delete using in-order successor for two-child nodes.
Compute single source shortest paths in a weighted Go graph using Dijkstra with container heap.
Compute the Levenshtein edit distance between two Go strings with insert, delete, and substitute operations.
Find the shortest path in an unweighted Go graph using BFS with a predecessor map for path reconstruction.
Perform topological sort on a Go DAG using DFS with cycle detection via tri-color marking.
Sort a Go slice by building a max heap in place then repeatedly extracting the maximum to the end.
Match a pattern in Go text using KMP with a precomputed failure function for linear time matching.
Solve the 0-1 knapsack problem in Go using dynamic programming with a rolling array for space optimization.
Compute the longest common subsequence of two Go strings using dynamic programming with table reconstruction.
Count inversions in a slice using a modified Go mergesort that counts crossings during the merge step.
Generate all primes up to n in Go using a segmented sieve of Eratosthenes for memory efficiency.
Sort a slice in place using Go quicksort with median-of-three pivot selection to avoid worst-case behavior.
Find all occurrences of a pattern in Go text using Rabin Karp with a rolling hash for O(n+m) average time.
Build a Go trie from a word list supporting prefix search and autocomplete suggestions ranked by frequency.
Implement a Go disjoint set union find with path compression and union by rank for near constant amortized time.
Reload configuration atomically using atomic.Value for zero-downtime config updates.
Encode a file to base64 in chunks for memory-efficient binary data transport.
Use bounded channels for backpressure in Go pipelines between producer and consumer.
Check if an IP address is within allowed CIDR ranges for network access control.
Implement a circuit breaker with state transitions and metrics for Go service protection.
Build a CLI with Cobra supporting flags subcommands and config precedence.
Set timeouts on HTTP client requests using context for preventing hanging connections.
Load config from environment variables with defaults and validation in Go.
Fan out parallel API calls with errgroup and limit concurrency in Go services.
Run parallel HTTP fetches with errgroup for concurrent fanout with first-error cancellation.
Use file locks for cross-process critical sections with flock in Go applications safely.
Use Go generics with type constraints for type-safe min and max functions.
Run tasks in a bounded goroutine pool with a job channel for controlled concurrency.
Log HTTP requests with a middleware including method path status and duration.
Implement a token bucket rate limiter as HTTP middleware for Go API throttling.
Retry operations with exponential backoff and jitter in Go for transient error handling.
Use weighted semaphore for concurrency limiting with different resource weights.
Compute an HMAC-SHA256 tag and compare it in constant time to avoid leaking the secret through timing.
Propagate cancellation and deadlines through a call tree using Go context, so abandoned work stops promptly.
Bound concurrent work by cost using a weighted semaphore, admitting tasks only while capacity remains.
Process a stream of jobs with a fixed number of goroutines, bounded channels and graceful completion.
Track hot counters with atomic operations instead of mutexes, exporting per-second rates and cumulative values for monitoring.
Parse newline-delimited JSON streams with bufio.Scanner, sizing buffers for long lines and isolating malformed records.
Log every request with chi middleware: request ids, durations, status codes, and route patterns instead of raw paths.
Trip a circuit breaker after consecutive failures, short-circuiting calls during an open period and probing recovery with a half-open state.
Resolve CLI configuration with explicit precedence from flags over environment over config file, with typed defaults and validation.
Derive a context with a deadline so downstream work is cancelled when the caller gives up, and propagate the reason through context errors.
Give outbound HTTP calls hard deadlines with context timeouts, propagating cancellation into DNS, connect, and body read phases.
Query and control Docker containers with the Go SDK, filtering by labels, streaming events, and reporting runtime stats.
Read configuration from environment variables with typed parsing and defaults, validating required fields at startup rather than at first use.
Run parallel HTTP fetches under one errgroup context so the first error cancels siblings and always reclaims goroutines.
Fan out calls to many shards with errgroup SetLimit bounding concurrency, merging partial results even when some shards fail.
Fetch several resources concurrently with errgroup so the first error cancels the rest and the combined call fails fast.
Throttle Fiber routes with a sliding-window rate limiter middleware, keying by API key with burst tolerance and custom 429 bodies.
Write generic min and max helpers constrained to ordered types, avoiding duplication across numeric and string collections.
Extract and verify JWT claims in Gin middleware, checking issuer and role before handlers, with claims injected into context.
Build a Go CI pipeline with matrix versions, module caching, lint gates, race-enabled tests, and release artifact uploads.
Batch independent Redis commands into pipelines and transactions, measuring round-trip savings and verifying atomic MULTI execution.
Configure the go-redis universal client for single, sentinel, and cluster topologies, with pool sizing and timeout discipline.
Run a hub that registers WebSocket clients into rooms, broadcasts messages to a room, and unregisters on disconnect or expiry.
Paginate PostgreSQL result sets with GORM using keyset conditions on indexed sort columns, stable under concurrent inserts.
Implement Relay-style cursor pagination with gqlgen resolvers, resolving edges and pageInfo from a keyset-ordered store.
Stop an HTTP server gracefully on SIGTERM, draining connections with a bounded context deadline before forcing closure.
Listen for termination signals and shut an HTTP server down gracefully so in-flight requests finish before the process exits.
Set per-call deadlines on gRPC clients, propagate cancellation through context, and classify DEADLINE_EXCEEDED versus CANCELED codes.
Decode a stream of JSON values from a reader without buffering the whole payload, using a decoder that reads records one at a time.
Compose HTTP handlers through middleware that wrap the next handler, adding logging, recovery, and request identifiers without duplication.
Tail MongoDB collection changes with the Go driver, filtering server-side, resuming by token, and timing out idle watches.
Stream multipart uploads in a Go handler with a memory threshold, per-file size caps, and non-blocking cleanup of partial files.
Harden an HTTP server with read, write, idle, and header timeouts so slow or hostile clients cannot pin connections open.
Drive PostgreSQL through a pgx connection pool with statement timeouts, health pings, and context-scoped transactions.
Detect PostgreSQL serialization failures in pgx transactions and retry the whole unit with backoff, aborting only on hard errors.
Expose Go runtime profiling endpoints on an internal port, sampling CPU flame graphs, heap snapshots, and goroutine dumps.
Implement a token bucket rate limiter that refills at a configured rate and allows a burst, guarding handlers against traffic spikes.
Retry idempotent HTTP requests on server errors and throttling responses, backing off between attempts and honouring context cancellation.
Retry transient failures with capped exponential backoff plus jitter, classifying errors by retryability and giving up with context.
Shield a slow loader with singleflight and a shared cache, collapsing concurrent misses into one fetch and serving stale during refresh.
Collapse duplicate concurrent requests for the same key into a single upstream call so a burst of callers does not stampede a slow dependency.
Adopt Go structured logging with slog: leveled JSON handlers, grouped attributes, log record routing, and child loggers with bound context.
Wrap failing dependencies with sony/gobreaker, opening the circuit after consecutive failures and probing recovery in half-open.
Run a parameterised query and scan each row into a struct, closing rows and checking the iteration error so resources are not leaked.
Guard outbound fetches against SSRF with an allowlist of hosts and schemes, blocking private networks and redirects to internal IPs.
Emit structured logs with the standard slog package so records carry typed key-value attributes that are easy to filter and correlate.
Recycle byte buffers with sync.Pool to cut allocation churn in hot paths, using Get/Put discipline and clearing on store.
Structure Go tests as a table of cases with subtests, so each scenario is named, isolated, and easy to extend with new rows.
Cover function branches with table-driven tests: declarative cases with names, parallel subtests, and precise failure output.
Implement a concurrency-safe token bucket with atomic refill math, per-key buckets, and TryTake plus blocking Take semantics.
Layer application config with Viper across files, environment variables with key replacer, and overrides bound to flags.
Keep WebSocket connections alive with application-level ping frames, tracking liveness with deadlines and cleaning dead peers.
Process a job channel with a fixed pool of workers, draining remaining jobs on shutdown and collecting per-worker stats safely.
Dispatch jobs to a fixed pool of workers through channels, bounding concurrency while processing a large queue of tasks.
Hash passwords with Argon2id and a random salt, encode parameters into a PHC string, and verify in constant time.
Store integer identifiers in compact 64-bit words with set, clear, union, intersection, counting, and ordered iteration.
Connect a fast producer to a slow consumer through a small buffered channel, then stop the pipeline cleanly on deadline.
Parse dotenv files with export prefixes, quoted values, inline comments, and strict key validation, returning a plain map.
Take an exclusive non-blocking flock around a critical section, reject a second holder, and reacquire after release.
Swap immutable configuration snapshots atomically so readers never take a lock, while validating each new version first.
Build an IP allowlist from CIDR prefixes and check IPv4 or IPv6 addresses without allocating or trusting raw strings.
Protect a flaky dependency with closed, open, and half-open states, a failure threshold, and a cooldown before probing again.
Compare API tokens without leaking length or prefix through timing by hashing both sides to fixed size and using subtle.
Derive one deadline for a multi-step operation, check the remaining budget before each call, and fail fast with a wrapped error.
Apply a per-request deadline with context.WithTimeout, classify timeout errors, and cap response reads in a Go HTTP client.