Documentation
¶
Overview ¶
Package lambdahttp normalises the AWS Lambda HTTP event shapes into standard *http.Request values and renders whatever an http.Handler writes back into the matching event-specific response shape.
Four inbound shapes are supported:
- API Gateway HTTP API, payload format 2.0 (events.APIGatewayV2HTTPRequest)
- API Gateway REST API proxy, payload format 1.0 (events.APIGatewayProxyRequest)
- Lambda Function URL (events.LambdaFunctionURLRequest)
- Application Load Balancer target group (events.ALBTargetGroupRequest)
Wiring a binary is one line:
lambda.Start(lambdahttp.New(mux, lambdahttp.Options{}).Handle)
or, when the deployment shape is known at build time, the per-shape entry point (HandleAPIGatewayV2, HandleAPIGatewayREST, HandleFunctionURL, HandleALB) which is typed and skips event sniffing.
Multiple Set-Cookie headers ¶
This is the reason the package exists. An auth service sets three cookies on a single login response (access token, refresh token, CSRF token) and every event shape represents that differently:
- HTTP API v2 and Function URL: the dedicated "cookies" []string response field. Inbound, request cookies also arrive in a "cookies" array and NOT as a Cookie header, so the adapter reconstructs the Cookie header — without that step http.Request.Cookie() finds nothing.
- REST v1 and ALB: multiValueHeaders["Set-Cookie"].
- ALB with multi-value headers disabled cannot express more than one Set-Cookie at all. The adapter detects that mode and fails with ErrMultiValueHeadersDisabled rather than silently dropping cookies.
Response streaming ¶
The buffered path here is deliberately split into NewRequest (inbound normalisation) and the rendering of a recorded response, so a future Function URL response-streaming handler can reuse NewRequest unchanged and supply its own streaming http.ResponseWriter.
Index ¶
- Constants
- Variables
- func DefaultSplitHeaders() []string
- func EventFrom(ctx context.Context) any
- func NewRequest(ctx context.Context, event any, opts Options) (*http.Request, error)
- type Adapter
- func (a *Adapter) Handle(ctx context.Context, payload json.RawMessage) (json.RawMessage, error)
- func (a *Adapter) HandleALB(ctx context.Context, evt events.ALBTargetGroupRequest) (events.ALBTargetGroupResponse, error)
- func (a *Adapter) HandleAPIGatewayREST(ctx context.Context, evt events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)
- func (a *Adapter) HandleAPIGatewayV2(ctx context.Context, evt events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error)
- func (a *Adapter) HandleFunctionURL(ctx context.Context, evt events.LambdaFunctionURLRequest) (events.LambdaFunctionURLResponse, error)
- type Kind
- type Options
- type StreamingHandler
- type Tristate
Constants ¶
const DefaultStreamDeadlineMargin = 5 * time.Second
DefaultStreamDeadlineMargin is how long before the invocation's own deadline the request context is cancelled. A Function URL invocation that reaches its timeout is killed mid-write and reported as an error; cancelling first lets the handler return, the runtime flush the last bytes and the response end cleanly, which for an SSE stream is the ordinary end of a segment that the client reconnects from.
Variables ¶
var ( // ErrUnsupportedEvent means the payload or value is not one of the four // supported Lambda HTTP event shapes. ErrUnsupportedEvent = errors.New("lambdahttp: unsupported lambda event") // ErrMultiValueHeadersDisabled means the response could not be rendered // because the ALB target group has multi-value headers turned off and the // handler emitted more than one value for some header. For an auth service // this is almost always more than one Set-Cookie, i.e. a login that would // otherwise half-succeed. ErrMultiValueHeadersDisabled = errors.New("lambdahttp: alb multi-value headers are disabled, response headers would be lost") // ErrBadRequestEvent means a well-formed event carried a field the adapter // could not turn into an *http.Request, such as an undecodable base64 body. ErrBadRequestEvent = errors.New("lambdahttp: malformed request event") )
Sentinel errors returned by the package. Every error the adapter produces wraps one of these (or an underlying encoding/parsing error) with context, so callers can match with errors.Is.
var ErrStreamWriteTimeout = errors.New("lambdahttp: stream write missed its deadline")
ErrStreamWriteTimeout is what a Write answers when the runtime did not take its bytes before the deadline the handler set.
Functions ¶
func DefaultSplitHeaders ¶
func DefaultSplitHeaders() []string
DefaultSplitHeaders returns the request headers the adapter splits on commas when they arrive comma-joined in a single-value header map. Each entry is a header whose first list element is the meaningful one, so http.Header.Get keeps returning something sensible after the split.
func EventFrom ¶
EventFrom returns the Lambda event a request was normalised from, or nil when the context did not come through this package. The concrete type is one of events.APIGatewayV2HTTPRequest, events.APIGatewayProxyRequest, events.LambdaFunctionURLRequest or events.ALBTargetGroupRequest, so handlers that need authorizer claims or the request context can type-switch on it.
func NewRequest ¶
NewRequest converts a supported Lambda HTTP event into an *http.Request that any http.Handler can serve unchanged. event must be one of events.APIGatewayV2HTTPRequest, events.APIGatewayProxyRequest, events.LambdaFunctionURLRequest or events.ALBTargetGroupRequest (pointers to those types are accepted too); anything else yields ErrUnsupportedEvent.
ctx becomes the request context, so the Lambda deadline and request ID stay reachable from the handler, and the original event is attached to it — see EventFrom.
It is exported so that alternative response paths, such as Function URL response streaming, can reuse the inbound normalisation as-is.
Types ¶
type Adapter ¶
type Adapter struct {
// contains filtered or unexported fields
}
Adapter serves Lambda HTTP events with an http.Handler.
func New ¶
New returns an Adapter that dispatches every supported Lambda HTTP event to h. opts may be the zero Options.
func (*Adapter) Handle ¶
func (a *Adapter) Handle(ctx context.Context, payload json.RawMessage) (json.RawMessage, error)
Handle is the auto-detecting entry point, suitable for lambda.Start. It sniffs the payload with Detect, dispatches to the matching per-shape entry point and marshals the result.
KindAPIGatewayV2 and KindFunctionURL carry the same request fields and the same response fields — status code, headers map, cookies array, body, isBase64Encoded — so confusing one for the other cannot change what reaches the client. (The v2 struct additionally serialises a null multiValueHeaders, which HTTP APIs ignore.)
func (*Adapter) HandleALB ¶
func (a *Adapter) HandleALB(ctx context.Context, evt events.ALBTargetGroupRequest) (events.ALBTargetGroupResponse, error)
HandleALB serves an Application Load Balancer target group event.
When the target group has multi-value headers enabled, EVERY header is returned in multiValueHeaders and the single-value headers map is left unset: AWS specifies one map or the other per mode, not a split across both, so a single-valued Content-Type or Location left in headers would be dropped. When the attribute is off, and the handler produced more than one value for any header (typically more than one Set-Cookie), the response cannot be expressed: HandleALB returns ErrMultiValueHeadersDisabled so the invocation fails visibly instead of a login half-succeeding with two of its three cookies missing.
func (*Adapter) HandleAPIGatewayREST ¶
func (a *Adapter) HandleAPIGatewayREST(ctx context.Context, evt events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)
HandleAPIGatewayREST serves an API Gateway REST API proxy (payload format 1.0) event. Headers with a single value go to headers, headers with several values — and Set-Cookie always — go to multiValueHeaders, so no key is ever present in both maps.
func (*Adapter) HandleAPIGatewayV2 ¶
func (a *Adapter) HandleAPIGatewayV2(ctx context.Context, evt events.APIGatewayV2HTTPRequest) (events.APIGatewayV2HTTPResponse, error)
HandleAPIGatewayV2 serves an API Gateway HTTP API payload format 2.0 event. Response headers are comma-joined into the headers map and every Set-Cookie goes to the dedicated cookies array; multiValueHeaders is left unset because HTTP APIs ignore it.
func (*Adapter) HandleFunctionURL ¶
func (a *Adapter) HandleFunctionURL(ctx context.Context, evt events.LambdaFunctionURLRequest) (events.LambdaFunctionURLResponse, error)
HandleFunctionURL serves a Lambda Function URL event. The response shape is the same as HTTP API v2: comma-joined headers plus a cookies array, which is the only way a Function URL can return more than one Set-Cookie.
type Kind ¶
type Kind string
Kind identifies a supported Lambda HTTP event shape.
const ( KindUnknown Kind = "" KindAPIGatewayV2 Kind = "apigateway-http-v2" KindAPIGatewayREST Kind = "apigateway-rest-v1" KindFunctionURL Kind = "function-url" KindALB Kind = "alb" )
The supported event shapes, plus KindUnknown for an unrecognised payload.
func Detect ¶
Detect identifies which Lambda HTTP event shape a raw payload is.
The discriminators are, in order: requestContext.elb (ALB), version "2.0" (HTTP API v2 or Function URL, told apart by the <id>.lambda-url.<region>.on.aws domain name because the two request payloads are otherwise identical), and finally a top-level httpMethod (REST proxy v1). Payloads matching none of those yield ErrUnsupportedEvent.
type Options ¶
type Options struct {
// StagePrefix is stripped from the front of the request path before the
// handler sees it, e.g. "/prod" or "prod". A default execute-api URL serves
// under https://<id>.execute-api.<region>.amazonaws.com/<stage>/, so the
// event path carries a stage segment that the handler's routes do not know
// about. Empty means strip nothing: the adapter never guesses a prefix.
//
// Note that stripping the stage also breaks __Host- cookie prefixes and
// Path-scoped refresh cookies unless a custom domain is used, because the
// browser still sees the stage segment.
StagePrefix string
// StripStageFromEvent strips requestContext.stage from the request path.
// It is an explicit opt-in, not a guess, and it is ignored when the stage
// is empty or "$default" (HTTP APIs and Function URLs, which serve at the
// root). StagePrefix wins when both are set.
StripStageFromEvent bool
// SplitHeaders lists request headers whose comma-joined single-value form
// is split back into separate http.Header values. AWS collapses repeated
// request headers into one comma-joined string in the single-value header
// map, which breaks equality checks such as
// r.Header.Get("X-Forwarded-Proto") == "https" behind CloudFront -> ALB.
//
// nil selects DefaultSplitHeaders. A non-nil empty slice disables
// splitting. Names are matched case-insensitively.
//
// Splitting is deliberately conservative: http.Header.Get returns only the
// first value, so splitting a header such as Cache-Control or Accept would
// hide the rest of the list from ordinary handlers.
SplitHeaders []string
// ALBMultiValueHeaders declares whether the ALB target group has the
// multi-value headers attribute enabled. Auto infers it from the event:
// the load balancer sends multiValueHeaders/multiValueQueryStringParameters
// only when the attribute is on.
//
// With the attribute off, a response carrying more than one value for any
// header — in practice, more than one Set-Cookie — cannot be expressed and
// the adapter returns ErrMultiValueHeadersDisabled instead of dropping it.
ALBMultiValueHeaders Tristate
// ALBInputDecoded declares that the load balancer delivers the request path
// and query-string values already URL-decoded. The default (false) matches
// documented ALB behaviour, where both arrive percent-encoded and are
// passed through untouched. API Gateway, by contrast, always decodes, and
// the adapter re-encodes its values itself.
ALBInputDecoded bool
// OnError, when set, receives every error the adapter handles internally:
// event normalisation failures, recovered handler panics, and unrenderable
// responses. It is an observability hook — the adapter still returns the
// error and/or an error status to the caller.
OnError func(context.Context, error)
}
Options configures an Adapter. The zero value is usable and makes no guesses: no path is stripped, ALB behaviour is inferred from the event, and the default comma-splitting header set is applied.
type StreamingHandler ¶
type StreamingHandler = func(context.Context, *events.LambdaFunctionURLRequest) (*events.LambdaFunctionURLStreamingResponse, error)
StreamingHandler is the handler shape lambda.StartHandlerFunc takes for a Function URL in RESPONSE_STREAM mode. An alias rather than a defined type, because lambda.StartHandlerFunc constrains its argument to the exact func type and a defined type would not satisfy it.
func NewStreamingHandler ¶
NewStreamingHandler serves Function URL requests with h, streaming whatever it writes. margin is how long before the invocation deadline the request context ends; zero selects DefaultStreamDeadlineMargin and a negative value disables it.