Documentation
¶
Overview ¶
Package response answers the typed operations of an Event Handler router (github.com/alessandrolattao/powertools-lambda-go/eventhandler): success responses with their cache headers, CSV bodies, and the error envelope. It also writes the server-sent events of a streaming handler (SSE).
A typed operation returns its result, or a *Error:
if errors.Is(err, pgx.ErrNoRows) {
return order{}, response.NotFound("orderNotFound", "no order with this id", nil)
}
return o, nil
and an eventhandler.Response when it sets its own status or headers:
return response.OK(orders, response.WithCacheMaxAge(time.Minute)), nil
An error answers with the envelope {"code","message","details","timestamp"}: a stable, camelCase code clients key on (to look up a translated text, for instance) and a free-form message meant for logs, never shown to users. The framework package renders it, and maps the errors of the Event Handler itself (404, validation, unsupported content type) to the same envelope.
Index ¶
- Variables
- func Accepted[T any](body T, opts ...Option) eventhandler.Response[T]
- func CSV(records [][]string, opts ...Option) (eventhandler.Response[[]byte], error)
- func Created[T any](body T, opts ...Option) eventhandler.Response[T]
- func Negotiate(accept string, rows any, opts ...Option) (eventhandler.Response[[]byte], error)
- func NoContent(opts ...Option) eventhandler.Response[[]byte]
- func OK[T any](body T, opts ...Option) eventhandler.Response[T]
- func SSE(w http.ResponseWriter, event, data string) error
- func StructsCSV(rows any, opts ...Option) (eventhandler.Response[[]byte], error)
- type Error
- func BadRequest(code, message string, details any) *Error
- func Conflict(code, message string, details any) *Error
- func Forbidden(code, message string, details any) *Error
- func InternalServerError(err error, code, message string, details any) *Error
- func NewError(status int, code, message string, details any) *Error
- func NotFound(code, message string, details any) *Error
- func PaymentRequired(code, message string, details any) *Error
- func TooManyRequests(code, message string, details any) *Error
- func Unauthorized(code, message string, details any) *Error
- func UnprocessableEntity(code, message string, details any) *Error
- type ErrorBody
- type Option
Constants ¶
This section is empty.
Variables ¶
var ErrSSEEventName = errors.New("the name of a server-sent event must be one line")
ErrSSEEventName is what SSE answers for an event name that is not one line: a CR or an LF in it would add fields of its own to the stream.
Functions ¶
func Accepted ¶
func Accepted[T any](body T, opts ...Option) eventhandler.Response[T]
Accepted answers 202 with body as JSON.
func Created ¶
func Created[T any](body T, opts ...Option) eventhandler.Response[T]
Created answers 201 with body as JSON.
func Negotiate ¶
Negotiate answers rows as CSV (StructsCSV) when accept, the request's Accept header, asks for text/csv, and as JSON otherwise. The response varies on Accept, so caches keep the two apart.
func NoContent ¶
func NoContent(opts ...Option) eventhandler.Response[[]byte]
NoContent answers 204 without a body.
func OK ¶
func OK[T any](body T, opts ...Option) eventhandler.Response[T]
OK answers 200 with body as JSON.
func SSE ¶
func SSE(w http.ResponseWriter, event, data string) error
SSE writes one server-sent event to w and flushes it to the client: an event line when event is not empty, a data line for each line of data, and the blank line that ends the event. event must be one line: one with a CR or an LF answers ErrSSEEventName, and nothing is written. data is split on every line break (CRLF, CR, LF). A streaming handler (framework.Container.Stream) sends each event with one call:
w.Header().Set("Content-Type", "text/event-stream")
if err := response.SSE(w, "price", `{"amount":42}`); err != nil {
return err
}
Any other error is the one writing or flushing failed with: the client went away, or w cannot flush.
func StructsCSV ¶
StructsCSV answers 200 with rows, a slice of structs or of pointers to structs, as CSV: a header row with the exported field names, then a row per element (empty for a nil pointer). A field is written with its MarshalText, else its driver.Valuer, else its plain value.
Types ¶
type Error ¶
type Error struct {
// Status is the HTTP status of the answer.
Status int
// Code is the stable, camelCase code clients key on.
Code string
// Message is for whoever reads the body in a log or a trace.
Message string
// Details carries what the client needs to act on the failure; it is
// written as JSON.
Details any
// Err is the failure behind a 5xx: the framework logs it, the client
// never sees it.
Err error
}
Error is a failure that answers the client with the error envelope. Return it from a typed operation; the framework writes it.
func InternalServerError ¶
InternalServerError is a 500 caused by err, which the framework reports once, at Error; the client gets the envelope, never err.
func NewError ¶
NewError returns the failure answering status with the envelope of code, message and details.
func PaymentRequired ¶
PaymentRequired is a 402.
func TooManyRequests ¶
TooManyRequests is a 429.
func Unauthorized ¶
Unauthorized is a 401.
func UnprocessableEntity ¶
UnprocessableEntity is a 422.
func (*Error) APIGatewayProxy ¶
func (e *Error) APIGatewayProxy() events.APIGatewayProxyResponse
APIGatewayProxy returns the envelope of e as an API Gateway REST API response (Lambda proxy integration, payload format 1.0), for a handler that answers the event itself rather than through a router.
func (*Error) APIGatewayV2 ¶
func (e *Error) APIGatewayV2() events.APIGatewayV2HTTPResponse
APIGatewayV2 returns the envelope of e as an API Gateway HTTP API response (payload format 2.0), for a handler that answers the event itself rather than through a router.
func (*Error) Write ¶
func (e *Error) Write(w http.ResponseWriter)
Write answers w with the envelope of e. An error is never cached.
type ErrorBody ¶
type ErrorBody struct {
Code string `json:"code"`
Message string `json:"message"`
Details any `json:"details,omitempty"`
Timestamp string `json:"timestamp"`
}
ErrorBody is the error envelope, what the client reads.
type Option ¶
Option sets a header of a success response.
func WithCacheMaxAge ¶
WithCacheMaxAge lets browsers and shared caches keep the response for d.
func WithCacheMaxAgeShared ¶
WithCacheMaxAgeShared lets browsers keep the response for browser and shared caches (CloudFront) for shared.