Documentation
¶
Overview ¶
httputil/json.go
Index ¶
- func BindJSON(r *http.Request, v any) error
- func BindJSONAllowUnknown(r *http.Request, v any) error
- func JSONError(w http.ResponseWriter, status int, code, message string)
- func JSONErrorSimple(w http.ResponseWriter, status int, message string)
- func SetJSONLogger(logger JSONLogger)
- func WriteJSON(w http.ResponseWriter, status int, v any)
- type ErrorResponse
- type JSONLogger
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BindJSON ¶ added in v0.1.19
BindJSON decodes the request body as JSON into v.
It returns a user-friendly error if the body is empty, malformed, or contains unknown fields. The error messages are safe to return to clients.
Example:
var req CreateUserRequest
if err := httputil.BindJSON(r, &req); err != nil {
httputil.JSONError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
func BindJSONAllowUnknown ¶ added in v0.1.19
BindJSONAllowUnknown is like BindJSON but permits unknown fields in the JSON. Use this when you want to be lenient about extra fields in the request. Like BindJSON, it rejects request bodies containing multiple JSON values.
func JSONError ¶
func JSONError(w http.ResponseWriter, status int, code, message string)
JSONError writes a structured JSON error with an error code and message.
func JSONErrorSimple ¶
func JSONErrorSimple(w http.ResponseWriter, status int, message string)
JSONErrorSimple is a shorthand for errors where the message itself is the code.
func SetJSONLogger ¶ added in v0.1.19
func SetJSONLogger(logger JSONLogger)
SetJSONLogger configures the logger used for JSON encoding errors. This should be called once during application startup.
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, status int, v any)
WriteJSON writes a JSON response with the given status code. If encoding fails, the error is logged (if a logger is configured via SetJSONLogger) because headers and status have already been sent and we can't send another response.
Invalid status codes (outside 100-599) are clamped to 500 Internal Server Error to prevent undefined behavior in net/http.
Types ¶
type ErrorResponse ¶
ErrorResponse is a standard JSON error envelope.
type JSONLogger ¶ added in v0.1.19
JSONLogger is a minimal interface for logging JSON encoding errors.