httputil

package
v0.1.36 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

httputil/json.go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BindJSON added in v0.1.19

func BindJSON(r *http.Request, v any) error

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

func BindJSONAllowUnknown(r *http.Request, v any) error

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

type ErrorResponse struct {
	Error   string `json:"error"`
	Message string `json:"message,omitempty"`
}

ErrorResponse is a standard JSON error envelope.

type JSONLogger added in v0.1.19

type JSONLogger interface {
	Error(msg string, args ...any)
}

JSONLogger is a minimal interface for logging JSON encoding errors.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL