response

package
v0.0.0-...-4391913 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 15 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
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 CSV

func CSV(records [][]string, opts ...Option) (eventhandler.Response[[]byte], error)

CSV answers 200 with records as a CSV document, downloaded as data.csv.

func Created

func Created[T any](body T, opts ...Option) eventhandler.Response[T]

Created answers 201 with body as JSON.

func Negotiate

func Negotiate(accept string, rows any, opts ...Option) (eventhandler.Response[[]byte], error)

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

func StructsCSV(rows any, opts ...Option) (eventhandler.Response[[]byte], error)

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 BadRequest

func BadRequest(code, message string, details any) *Error

BadRequest is a 400.

func Conflict

func Conflict(code, message string, details any) *Error

Conflict is a 409.

func Forbidden

func Forbidden(code, message string, details any) *Error

Forbidden is a 403.

func InternalServerError

func InternalServerError(err error, code, message string, details any) *Error

InternalServerError is a 500 caused by err, which the framework reports once, at Error; the client gets the envelope, never err.

func NewError

func NewError(status int, code, message string, details any) *Error

NewError returns the failure answering status with the envelope of code, message and details.

func NotFound

func NotFound(code, message string, details any) *Error

NotFound is a 404.

func PaymentRequired

func PaymentRequired(code, message string, details any) *Error

PaymentRequired is a 402.

func TooManyRequests

func TooManyRequests(code, message string, details any) *Error

TooManyRequests is a 429.

func Unauthorized

func Unauthorized(code, message string, details any) *Error

Unauthorized is a 401.

func UnprocessableEntity

func UnprocessableEntity(code, message string, details any) *Error

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) Body

func (e *Error) Body() ErrorBody

Body returns the envelope of e, stamped now.

func (*Error) Error

func (e *Error) Error() string

Error describes the failure, its cause included.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the cause.

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

type Option func(http.Header)

Option sets a header of a success response.

func WithCacheMaxAge

func WithCacheMaxAge(d time.Duration) Option

WithCacheMaxAge lets browsers and shared caches keep the response for d.

func WithCacheMaxAgeShared

func WithCacheMaxAgeShared(browser, shared time.Duration) Option

WithCacheMaxAgeShared lets browsers keep the response for browser and shared caches (CloudFront) for shared.

func WithHeader

func WithHeader(name, value string) Option

WithHeader sets a header.

func WithNoCache

func WithNoCache() Option

WithNoCache forbids caching the response.

Jump to

Keyboard shortcuts

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