go
36 lines · 1 tab
Leah Thompson
Jan 2026
1 tab
package middleware
import (
"net"
"net/http"
"net/netip"
)
func AllowCIDRs(prefixes []netip.Prefix) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
addr, err := netip.ParseAddr(host)
if err != nil {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
ok := false
for _, p := range prefixes {
if p.Contains(addr) {
ok = true
break
}
}
if !ok {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
}
1 file · go
Explain with highlit
For internal admin endpoints, I often add a network allowlist in addition to auth. The tricky part is deciding which IP to trust: if you’re behind a proxy, you might need X-Forwarded-For, but only if the proxy is controlled by you. The middleware below parses CIDRs into netip.Prefix and checks whether the client address falls inside. I keep the allowlist immutable and fail closed: if the IP can’t be parsed, access is denied. In production, I also log denials with a request ID so you can debug misconfigured proxies without printing sensitive headers. The key is to treat this as a defense-in-depth layer, not your only protection.
Related snips
go
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
go
observability
build
by Leah Thompson
1 tab
ruby
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
jwt
authentication
api
by Kai Nakamura
2 tabs
typescript
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
typescript
reliability
retry
by codesnips
2 tabs
go
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
go
postgres
transactions
by Leah Thompson
1 tab
bash
#!/usr/bin/env bash
set -euo pipefail
export VAULT_ADDR="https://vault.internal:8200"
export VAULT_TOKEN="${VAULT_TOKEN:?missing VAULT_TOKEN}"
Secrets management with environment isolation and Vault
secrets-management
vault
environment-variables
by Kai Nakamura
1 tab
typescript
import { randomBytes, createHash } from "crypto";
import jwt from "jsonwebtoken";
import { RefreshTokenStore } from "./store";
const ACCESS_SECRET = process.env.ACCESS_SECRET!;
const ACCESS_TTL = "15m";
JWT access + refresh token rotation (conceptual)
security
node
jwt
by codesnips
3 tabs
Share this code
Here's the card — post it anywhere.