Documentation
¶
Overview ¶
Package json provides utilities for handling JSON requests and responses.
Index ¶
- func ReadBody[T any](req *http.Request) (T, error)
- type Problem
- type Response
- func (r *Response) Accepted(opts ...ResponseOption)
- func (r *Response) AcceptedWithMessage(message string)deprecated
- func (r *Response) BadRequest(opts ...ResponseOption)
- func (r *Response) BadRequestWithMessage(message string)deprecated
- func (r *Response) BadRequestWithMessages(responseMessage, logMessage string)deprecated
- func (r *Response) Conflict(opts ...ResponseOption)
- func (r *Response) ConflictWithMessage(message string)deprecated
- func (r *Response) ConflictWithMessages(responseMessage, logMessage string)deprecated
- func (r *Response) Created(opts ...ResponseOption)
- func (r *Response) CreatedWithMessage(message string)deprecated
- func (r *Response) CreatedWithURI(uri string)deprecated
- func (r *Response) CreatedWithURIAndMessage(uri string, message string)deprecated
- func (r *Response) Data(status int, data any)
- func (r *Response) Forbidden(opts ...ResponseOption)
- func (r *Response) ForbiddenWithMessage(message string)deprecated
- func (r *Response) ForbiddenWithMessages(responseMessage, logMessage string)deprecated
- func (r *Response) InternalServerError(opts ...ResponseOption)
- func (r *Response) InternalServerErrorWithMessage(err error, message string)deprecated
- func (r *Response) InternalServerErrorWithMessages(err error, responseMessage string, logMessage string)deprecated
- func (r *Response) InvalidInput(opts ...ResponseOption)
- func (r *Response) InvalidInputWithMessage(err error, message string)deprecated
- func (r *Response) InvalidInputWithMessages(err error, responseMessage, logMessage string)deprecated
- func (r *Response) NoContent(opts ...ResponseOption)
- func (r *Response) NotAcceptable(opts ...ResponseOption)
- func (r *Response) NotAcceptableWithMessage(message string)deprecated
- func (r *Response) NotAcceptableWithMessages(responseMessage, logMessage string)deprecated
- func (r *Response) NotFound(opts ...ResponseOption)
- func (r *Response) NotFoundWithMessage(message string)deprecated
- func (r *Response) NotFoundWithMessages(responseMessage, logMessage string)deprecated
- func (r *Response) NotImplemented(opts ...ResponseOption)
- func (r *Response) OK(opts ...ResponseOption)
- func (r *Response) Problem(status int, p Problem, opts ...ResponseOption)
- func (r *Response) ServiceUnavailable(opts ...ResponseOption)
- func (r *Response) Unauthorized(opts ...ResponseOption)
- func (r *Response) UnauthorizedWithMessage(message string)deprecated
- func (r *Response) UnauthorizedWithMessages(responseMessage, logMessage string)deprecated
- func (r *Response) UnprocessableEntity(opts ...ResponseOption)
- func (r *Response) WithStatus(code int, opts ...ResponseOption)
- type ResponseOption
- func Data(data any) ResponseOption
- func Header(key, value string) ResponseOption
- func Location(uri string) ResponseOption
- func LogErr(err error) ResponseOption
- func LogField(key string, value any) ResponseOption
- func LogMessage(msg string) ResponseOption
- func PublicMessage(msg string) ResponseOption
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Problem ¶ added in v0.68.0
type Problem struct {
// Type is a URI reference identifying the problem type. Defaults to
// "about:blank" (RFC 9457 section 3.1) when empty. Consumers MUST use
// Type, not Status, as the problem's primary identifier.
Type string
// Title is a short, human-readable summary. It should stay stable
// across occurrences of this problem type, except for localization.
Title string
// Status is the HTTP status code, advisory only -- the response's
// actual status line is authoritative. Left zero, it is set to the
// status code passed to Problem.
Status int
// Detail is a human-readable explanation specific to this occurrence.
// It should help the client correct the problem, not aid debugging.
Detail string
// Instance is a URI reference identifying this specific occurrence.
Instance string
// Extensions carries problem-type-specific members (e.g. a
// machine-readable "reason" code) as additional top-level JSON members
// alongside type/title/status/detail/instance (RFC 9457 section 3.2). A
// key colliding with one of those five names is dropped in favour of
// the standard member.
Extensions map[string]any
}
Problem is an RFC 9457 Problem Details object. Every field is optional per the RFC; Type defaults to "about:blank" and Status is filled in from the status code passed to (*Response).Problem when left zero, so the common case only needs Title (and Detail, for an occurrence-specific message).
type Response ¶
type Response struct {
Writer http.ResponseWriter
// contains filtered or unexported fields
}
Response simplifies sending structured JSON responses and logging errors.
func NewResponse ¶
func NewResponse(w http.ResponseWriter) *Response
NewResponse creates a new Response helper with the provided ResponseWriter.
func NewResponseFromRequest ¶ added in v0.59.0
func NewResponseFromRequest(w http.ResponseWriter, r *http.Request) *Response
NewResponseFromRequest creates a Response that logs using the zerolog logger stored in r's context. All context fields — request_id, principal, auth_source, method, url (the full pre-strip path), remote_addr, and user_agent — are present because AddResource injects them into the context logger before calling the resource handler.
Prefer this over NewResponseWithLogger in HTTP handlers.
func NewResponseWithLogger
deprecated
NewResponseWithLogger creates a new Response helper with a logger that includes request metadata.
Deprecated: Use NewResponseFromRequest in HTTP handlers to automatically inherit the request-scoped context logger (carrying request_id, principal, etc.). NewResponseWithLogger remains useful when an explicit logger is needed (e.g. tests).
func (*Response) Accepted ¶ added in v0.58.0
func (r *Response) Accepted(opts ...ResponseOption)
Accepted sends a 202 Accepted response.
func (*Response) AcceptedWithMessage
deprecated
added in
v0.45.5
func (*Response) BadRequest ¶ added in v0.58.0
func (r *Response) BadRequest(opts ...ResponseOption)
BadRequest sends a 400 Bad Request response.
func (*Response) BadRequestWithMessage
deprecated
func (*Response) BadRequestWithMessages
deprecated
func (*Response) Conflict ¶ added in v0.58.0
func (r *Response) Conflict(opts ...ResponseOption)
Conflict sends a 409 Conflict response.
func (*Response) ConflictWithMessage
deprecated
func (*Response) ConflictWithMessages
deprecated
func (*Response) Created ¶ added in v0.58.0
func (r *Response) Created(opts ...ResponseOption)
Created sends a 201 Created response.
Example ¶
A handler answers with a helper named after the status. The options say what goes to the client.
package main
import (
"fmt"
"net/http/httptest"
"github.com/dioad/net/http/json"
)
func main() {
w := httptest.NewRecorder()
json.NewResponse(w).Created(
json.Location("/things/42"),
json.Data(map[string]any{"id": 42}),
)
fmt.Println(w.Code, w.Header().Get("Location"))
fmt.Print(w.Body.String())
}
Output: 201 /things/42 {"id":42,"message":"created"}
func (*Response) CreatedWithMessage
deprecated
func (*Response) CreatedWithURI
deprecated
added in
v0.53.0
func (*Response) CreatedWithURIAndMessage
deprecated
added in
v0.53.0
func (*Response) Forbidden ¶ added in v0.58.0
func (r *Response) Forbidden(opts ...ResponseOption)
Forbidden sends a 403 Forbidden response.
func (*Response) ForbiddenWithMessage
deprecated
added in
v0.39.0
func (*Response) ForbiddenWithMessages
deprecated
added in
v0.39.0
func (*Response) InternalServerError ¶ added in v0.58.0
func (r *Response) InternalServerError(opts ...ResponseOption)
InternalServerError sends a 500 Internal Server Error response.
Example ¶
LogErr keeps the cause of a failure in the server's log, and PublicMessage says what the client is told instead.
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"github.com/rs/zerolog"
"github.com/dioad/net/http/json"
)
func main() {
logger := zerolog.New(os.Stdout)
r := httptest.NewRequestWithContext(logger.WithContext(context.Background()), http.MethodGet, "/things/42", nil)
w := httptest.NewRecorder()
json.NewResponseFromRequest(w, r).InternalServerError(
json.LogErr(errors.New("connection refused")),
json.LogMessage("failed to load thing"),
json.PublicMessage("try again later"),
)
fmt.Println(w.Code)
fmt.Print(w.Body.String())
}
Output: {"level":"error","error":"connection refused","message":"failed to load thing"} 500 {"error":"try again later"}
func (*Response) InternalServerErrorWithMessage
deprecated
func (*Response) InternalServerErrorWithMessages
deprecated
func (r *Response) InternalServerErrorWithMessages(err error, responseMessage string, logMessage string)
InternalServerErrorWithMessages sends a 500 Internal Server Error response with responseMessage as the public message, and err and logMessage logged.
Deprecated: Use InternalServerError() with options instead.
func (*Response) InvalidInput ¶ added in v0.58.0
func (r *Response) InvalidInput(opts ...ResponseOption)
InvalidInput sends a 400 Bad Request response for invalid input.
func (*Response) InvalidInputWithMessage
deprecated
func (*Response) InvalidInputWithMessages
deprecated
func (*Response) NoContent ¶
func (r *Response) NoContent(opts ...ResponseOption)
NoContent sends a 204 No Content response.
func (*Response) NotAcceptable ¶ added in v0.58.0
func (r *Response) NotAcceptable(opts ...ResponseOption)
NotAcceptable sends a 406 Not Acceptable response.
func (*Response) NotAcceptableWithMessage
deprecated
func (*Response) NotAcceptableWithMessages
deprecated
func (*Response) NotFound ¶ added in v0.58.0
func (r *Response) NotFound(opts ...ResponseOption)
NotFound sends a 404 Not Found response.
func (*Response) NotFoundWithMessage
deprecated
func (*Response) NotFoundWithMessages
deprecated
func (*Response) NotImplemented ¶ added in v0.68.0
func (r *Response) NotImplemented(opts ...ResponseOption)
NotImplemented sends a 501 Not Implemented response.
func (*Response) Problem ¶ added in v0.68.0
func (r *Response) Problem(status int, p Problem, opts ...ResponseOption)
Problem sends an RFC 9457 "application/problem+json" response. status sets the HTTP status line; p.Status is set to status when p.Status is zero, since RFC 9457 requires the two to match.
opts accepts LogErr, LogMessage, LogField and Header/Location for side effects, exactly as the other Response methods do. Data and PublicMessage do not apply to a Problem body -- there is no message-merging step to plug them into -- and are dropped with a logged warning if passed.
func (*Response) ServiceUnavailable ¶ added in v0.68.0
func (r *Response) ServiceUnavailable(opts ...ResponseOption)
ServiceUnavailable sends a 503 Service Unavailable response.
func (*Response) Unauthorized ¶ added in v0.58.0
func (r *Response) Unauthorized(opts ...ResponseOption)
Unauthorized sends a 401 Unauthorized response.
func (*Response) UnauthorizedWithMessage
deprecated
added in
v0.39.0
func (*Response) UnauthorizedWithMessages
deprecated
added in
v0.39.0
func (*Response) UnprocessableEntity ¶ added in v0.68.0
func (r *Response) UnprocessableEntity(opts ...ResponseOption)
UnprocessableEntity sends a 422 Unprocessable Entity response.
func (*Response) WithStatus ¶ added in v0.58.0
func (r *Response) WithStatus(code int, opts ...ResponseOption)
WithStatus sends a response with a custom status code.
type ResponseOption ¶ added in v0.69.0
type ResponseOption interface {
// contains filtered or unexported methods
}
ResponseOption represents a configuration option for responses.
func Data ¶ added in v0.58.0
func Data(data any) ResponseOption
Data includes structured data in the response.
func Header ¶ added in v0.58.0
func Header(key, value string) ResponseOption
Header sets a custom response header.
func Location ¶ added in v0.58.0
func Location(uri string) ResponseOption
Location sets the Location header (typically for 201 Created responses).
func LogErr ¶ added in v0.58.0
func LogErr(err error) ResponseOption
LogErr includes an underlying error for server-side logging.
func LogField ¶ added in v0.72.0
func LogField(key string, value any) ResponseOption
LogField adds a structured field to the Response's logger, so it appears on every event the Response logs. On a Response from NewResponseFromRequest that logger is the request's context logger, so the field is also on the access log line and on anything else logged for the request afterwards. The field is never sent to the client.
Use a snake_case key, and do not log secrets or credentials. A Response with no logger ignores it.
Example ¶
LogField adds a field to the request's logger, so that the access log line the server writes after the handler returns carries it.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"github.com/rs/zerolog"
"github.com/dioad/net/http/json"
)
func main() {
logger := zerolog.New(os.Stdout)
r := httptest.NewRequestWithContext(logger.WithContext(context.Background()), http.MethodPost, "/events", nil)
w := httptest.NewRecorder()
json.NewResponseFromRequest(w, r).Accepted(json.LogField("event_type", "agent.registered"))
// The server's request log does this once the handler has returned.
zerolog.Ctx(r.Context()).Info().Msg("accessLog")
fmt.Print(w.Body.String())
}
Output: {"level":"info","event_type":"agent.registered","message":"accessLog"} {"message":"accepted"}
func LogMessage ¶ added in v0.58.0
func LogMessage(msg string) ResponseOption
LogMessage provides a custom message for server logs (separate from public message).
func PublicMessage ¶ added in v0.58.0
func PublicMessage(msg string) ResponseOption
PublicMessage sets the message sent to the client (overrides default).