package middleware
import (
"net/http"
"golang.org/x/time/rate"
)
func RateLimit(l *rate.Limiter) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !l.Allow() {
http.Error(w, "too many requests", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
}
If you expose an API to the public internet, you need a basic guardrail against bursts. I like a token bucket with rate.NewLimiter because it’s easy to reason about: steady-state rate plus a burst capacity. The middleware checks Allow() and returns 429 quickly when the limit is exceeded, which protects your database and downstream services. The important detail is scope: a global limiter is useful for protecting the whole service, but per-client limiting is usually better. In production, I combine this with an IP-based key (or authenticated principal) and a shared store if I need global enforcement across instances. Even as a local limiter, it’s a helpful first line of defense and keeps your service from getting overwhelmed by accidental client loops.
Related snips
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
package files
import (
"context"
"time"
Presigned S3 upload URLs (AWS SDK v2)
package deps
import (
"net"
"net/http"
"time"
HTTP client tuned for production: timeouts, transport, and connection reuse
package api
import (
"io"
"net/http"
"os"
Safe multipart uploads using temp files (bounded memory)
Share this code
Here's the card — post it anywhere.