go 22 lines · 1 tab

Enforce JSON Content-Type and method early in handlers

Leah Thompson Jan 2026
1 tab
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)
  })
}
1 file · go Explain with highlit

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

Share this code

Here's the card — post it anywhere.

Enforce JSON Content-Type and method early in handlers — share card
Link copied