package api
import (
"net/http"
"strings"
)
func RequireJSON(method string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != method {
w.Header().Set("Allow", method)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
ct := r.Header.Get("Content-Type")
if ct != "" && !strings.HasPrefix(ct, "application/json") {
http.Error(w, "unsupported media type", http.StatusUnsupportedMediaType)
return
}
next.ServeHTTP(w, r)
})
}
A lot of handler complexity disappears if you reject bad requests early. I enforce the HTTP method (POST, PUT, etc.) and require Content-Type: application/json before attempting to decode. This prevents confusing errors where clients send form-encoded payloads or forget headers and then get a generic 400. I also keep the check tolerant of charset parameters (application/json; charset=utf-8). In production, this improves observability because you can return a specific error code like UNSUPPORTED_MEDIA_TYPE rather than a generic “bad request.” It also helps security: you avoid accidentally parsing unexpected formats. Combined with http.MaxBytesReader and strict JSON decoding, this becomes a clean perimeter for request parsing.
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.