Graceful Shutdown Context Signal
Stop an HTTP server gracefully on SIGTERM, draining connections with a bounded context deadline before forcing closure.
Page 8 of 8
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.
Generate URL-safe tokens from crypto/rand with an entropy floor, plus unbiased numeric codes using crypto/rand.Int.
Issue a random CSRF cookie on safe requests and require a matching header on unsafe methods using constant-time comparison.
Decode CSV rows into typed structs with header checks, per-line error context, and rejection of negative numeric fields.
Coalesce bursts of events into one delayed function call using time.AfterFunc and a mutex-protected timer per debouncer.
Merge layered JSON-like configuration maps recursively so nested objects combine while scalar overrides replace base values.
Resolve a hostname through the default resolver with a context deadline, sort the addresses, and surface lookup failures clearly.
Collect every invalid signup field with errors.Join, then inspect the combined error using errors.As and Unwrap.
Send If-None-Match on repeat HTTP requests, handle 304 responses, and reuse the stored body when nothing changed.
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 command-line tool in Go using Cobra with subcommands, persistent flags, shell completion, help templates, and configuration loading from environment.
Implement CORS middleware in Go with configurable allowed origins, methods, headers, preflight request handling, and credential support for cross-origin API.
Handle multipart file uploads in Go with size limits, MIME type validation, unique filename generation, streaming to disk without buffering entire file, and.
Validate form data in Go using struct tags with the validator package, custom validation functions, nested struct validation, and human-readable error.
Create a gRPC server in Go with protobuf service definitions, interceptor middleware for logging and auth, graceful shutdown, health checks, and reflection.
Make HTTP requests in Go with retry logic, exponential backoff, context-based timeouts, connection pooling, and response decoding to typed structs using.
Create a production-ready HTTP server in Go with middleware chaining, graceful shutdown, request logging, CORS handling, and context-based timeouts. Uses.
Generate and validate JWT tokens in Go using the golang-jwt package with custom claims, token expiration, and middleware for protected HTTP routes. Includes.