go
37 lines · 1 tab
Leah Thompson
Jan 2026
1 tab
package api
import (
"io"
"net/http"
"os"
)
func Upload(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 20<<20) // 20 MiB
if err := r.ParseMultipartForm(20 << 20); err != nil {
http.Error(w, "invalid upload", http.StatusBadRequest)
return
}
f, _, err := r.FormFile("file")
if err != nil {
http.Error(w, "missing file", http.StatusBadRequest)
return
}
defer f.Close()
tmp, err := os.CreateTemp("", "upload-*")
if err != nil {
http.Error(w, "server error", http.StatusInternalServerError)
return
}
defer os.Remove(tmp.Name())
defer tmp.Close()
if _, err := io.Copy(tmp, f); err != nil {
http.Error(w, "failed to save", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
1 file · go
Explain with highlit
Multipart uploads are a common DOS vector if you let them allocate unbounded memory. I cap the request with http.MaxBytesReader, keep ParseMultipartForm bounded, and copy the file stream into a temp file using io.Copy. This avoids holding the whole file in RAM and gives you an artifact you can scan, validate, and then push to object storage. The other detail is cleanup: if any validation fails, the temp file should be removed, and file descriptors must be closed. In production I also validate MIME type by sniffing the first bytes rather than trusting the client header, and I track upload metrics (bytes, errors) so abuse is visible. This pattern is pragmatic and safe for most services.
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.