go
58 lines · 1 tab
Leah Thompson
Jan 2026
1 tab
package middleware
import (
"context"
"net/http"
"strings"
"time"
"github.com/MicahParks/keyfunc"
"github.com/golang-jwt/jwt/v5"
)
type ctxKey string
const subjectKey ctxKey = "subject"
func Subject(ctx context.Context) (string, bool) {
v := ctx.Value(subjectKey)
s, ok := v.(string)
return s, ok
}
func JWTAuth(jwksURL, issuer, audience string) (func(http.Handler) http.Handler, error) {
jwks, err := keyfunc.Get(jwksURL, keyfunc.Options{
RefreshInterval: 5 * time.Minute,
RefreshTimeout: 2 * time.Second,
})
if err != nil {
description: "To get useful traces, you need propagation and a real exporter. I set a global `TextMapPropagator` (`TraceContext` + `Baggage`) so inbound headers connect spans across services. Then I configure an OTLP exporter and a batch span processor so tracing overhead stays low. I also explicitly set a sampler: `ParentBased(TraceIDRatioBased(0.1))` is a common starting point that respects upstream sampling and keeps costs predictable. The other key piece is resource attributes like `service.name`, which is how traces are grouped in most backends. Once this is initialized, you can start spans in handlers with `otel.Tracer("...").Start(ctx, ...)` and get end-to-end visibility without special log parsing.",
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
tokenStr := strings.TrimPrefix(auth, "Bearer ")
token, err := jwt.Parse(tokenStr, jwks.Keyfunc, jwt.WithIssuer(issuer), jwt.WithAudience(audience))
if err != nil || !token.Valid {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
sub, _ := claims["sub"].(string)
ctx := context.WithValue(r.Context(), subjectKey, sub)
next.ServeHTTP(w, r.WithContext(ctx))
})
}, nil
description: "I like feature flags that are boring at runtime: reads should be lock-free and refresh should happen in the background. The pattern here stores a JSON flag snapshot in an `atomic.Value`, which makes reads cheap and race-free. A ticker refreshes the snapshot periodically from a backend (S3, database, config service) using a short `context.WithTimeout`. If refresh fails, we keep the last good snapshot, which is usually the safest behavior in production. The other key is exposing a small API (`Enabled("new_checkout")`) so call sites don’t learn about storage formats. This approach works well for “static-ish” flags like gradual rollouts and kill switches. For targeting by user, you can extend the model later, but the baseline stays simple and safe under load.",
1 file · go
Explain with highlit
JWT auth is easy to get subtly wrong, especially around key rotation. Instead of hard-coding public keys, I fetch JWKS and cache it with a refresh interval so new signing keys are accepted quickly. I still validate iss and aud so tokens from other environments can't be replayed. The middleware stores the sub claim in context and keeps error messages intentionally bland (unauthorized) to avoid leaking details. One operational tip: refresh timeouts should be short so a slow IdP doesn't block requests, and refresh failures should leave the last good keyset in place. With this setup, rotations become boring and you avoid the "midnight auth outage" pattern.
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.