package api
import (
"encoding/json"
"net/http"
)
func WriteJSON(w http.ResponseWriter, status int, v any) {
b, err := json.Marshal(v)
if err != nil {
http.Error(w, "server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_, _ = w.Write(b)
}
I like explicit response helpers because they prevent subtle inconsistencies: missing Content-Type, forgetting Cache-Control, or writing headers after the body has started. A WriteJSON function centralizes the “happy path” and makes error handling consistent too. The key is to set headers before WriteHeader, and to handle json.Marshal errors (which can happen if you accidentally include channels, funcs, or cyclic data). In production, I also add an option to pretty-print for non-prod environments, and I make sure errors are not leaking internal messages. This helper is intentionally small: it doesn’t try to be a framework, it just standardizes the output contract. When combined with a typed error-to-HTTP mapping, you get predictable responses that are easy to test with httptest and easy to consume from clients.
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.