package api
import (
"encoding/json"
"net/http"
)
func WriteJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
}
}
func WriteError(w http.ResponseWriter, status int, code string, details any) {
payload := map[string]any{"error": code}
if details != nil {
payload["details"] = details
}
WriteJSON(w, status, payload)
}
One of the easiest ways to reduce frontend complexity is to be consistent about API responses. I keep a small helper that always sets Content-Type: application/json; charset=utf-8, uses a stable error envelope (error + optional details), and returns correct status codes. The tricky part is not overengineering: you don’t need a framework to do this, just a couple of functions that every handler uses. I also make sure JSON encoding errors are handled safely (by writing a plain 500 rather than partial JSON). In production, this helps with observability too: logs and APM can key off a stable error code instead of parsing freeform messages. It’s small glue code, but it makes the whole API feel “designed,” not accidental.
Related snips
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
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
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
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
createdAt: String!
GraphQL API with Spring Boot
Share this code
Here's the card — post it anywhere.