Documentation
¶
Overview ¶
Package http routes native AWS Lambda HTTP events with isolated request state.
New constructs a Router. Register method/path handlers with Router.Get, Router.Post or Router.Handle, and compose middleware with Router.Use. Router.Resolve accepts API Gateway, Function URL and ALB event envelopes. Handlers receive RequestContext with a native net/http request and route data.
Response and lifecycle ¶
Handlers can return application values, explicit responses or native HTTP responses; conversion preserves status, headers, cookies and binary encoding. The streaming API supports the Lambda response-streaming lifecycle. See the guide before mixing buffered responses, owned bodies and streaming operations.
Request stores isolate invocation state; the router's shared store is explicitly application-wide. Register routes during initialization. Optional http/metrics and http/tracer modules add EMF and OpenTelemetry without bringing those dependencies into this core router.
For usage and compatibility details, see the user guide.
Index ¶
- func HandlerResultToWebResponse(value any) (*nethttp.Response, error)
- func IsALBEvent(value any) bool
- func IsAPIGatewayProxyEventV1(value any) bool
- func IsAPIGatewayProxyEventV2(value any) bool
- func IsExtendedAPIGatewayProxyResult(value any) bool
- func IsHTTPMethod(method string) bool
- func Streamify(handler func(context.Context, jsonv1.RawMessage, io.Writer) error) func(context.Context, jsonv1.RawMessage) (*ResponseStream, error)
- type CORSOptions
- type Check
- type CompressionOptions
- type ErrorHandler
- type HTTPError
- type Handler
- type InvalidEventError
- type InvalidHTTPMethodError
- type Middleware
- type Next
- type Options
- type ParameterValidationError
- type ProxyResponse
- type RequestChecks
- type RequestContext
- type RequestConversionError
- type Response
- type ResponseChecks
- type ResponseStream
- type ResponseType
- type Router
- func (r *Router) Delete(path string, h Handler, m ...Middleware) error
- func (r *Router) Get(path string, h Handler, m ...Middleware) error
- func (r *Router) Handle(method, path string, handler Handler, middleware ...Middleware) error
- func (r *Router) HandleRegex(method, pattern string, handler Handler, middleware ...Middleware) error
- func (r *Router) Head(path string, h Handler, m ...Middleware) error
- func (r *Router) IncludeRouter(child *Router, prefix string) error
- func (r *Router) MethodNotAllowed(handler ErrorHandler)
- func (r *Router) NotFound(handler ErrorHandler)
- func (r *Router) OnError(name string, handler ErrorHandler)
- func (r *Router) Options(path string, h Handler, m ...Middleware) error
- func (r *Router) Patch(path string, h Handler, m ...Middleware) error
- func (r *Router) Post(path string, h Handler, m ...Middleware) error
- func (r *Router) Put(path string, h Handler, m ...Middleware) error
- func (r *Router) Resolve(ctx context.Context, event any) (ProxyResponse, error)
- func (r *Router) ResolveStream(ctx context.Context, event any, destination io.Writer) error
- func (r *Router) Use(middleware ...Middleware)
- type Store
- type StreamPanicError
- type ValidatedData
- type ValidationConfig
- type ValidationIssue
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HandlerResultToWebResponse ¶
HandlerResultToWebResponse converts a handler result with the default 200 status.
func IsALBEvent ¶
func IsHTTPMethod ¶
func Streamify ¶
func Streamify(handler func(context.Context, jsonv1.RawMessage, io.Writer) error) func(context.Context, jsonv1.RawMessage) (*ResponseStream, error)
Streamify adapts a synchronous stream-writing handler to lambda.Start. Place Logger/Tracer wrappers inside handler so cleanup covers the entire body copy. Errors before the first write are invocation errors; subsequent errors reach the Lambda SDK through Read and can be reported as Runtime API error trailers.
Types ¶
type CORSOptions ¶
type CORSOptions struct {
Origin *string
Origins []string
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
Credentials bool
MaxAge *float64
}
CORSOptions preserves the reference distinction between a single origin and an origin array. Origins takes precedence over Origin when non-nil. Nil lists use the reference defaults; non-nil empty lists disable the corresponding list.
type Check ¶
Check adapts Parser, Validation or application schemas without a module dependency. Nonempty issues reject a value; operational errors remain distinct.
type CompressionOptions ¶
CompressionOptions selects gzip (default) or deflate (the zlib format). A nil Threshold uses 1024 bytes; compression requires a strictly larger body.
type ErrorHandler ¶
type ErrorHandler func(error, *RequestContext) (any, error)
type HTTPError ¶
type HTTPError struct {
StatusCode int `json:"statusCode"`
Type string `json:"error"`
Message string `json:"message"`
Details any `json:"details,omitempty"`
Cause error `json:"-"`
}
HTTPError represents the reference's named HTTP error classes.
func NewHTTPError ¶
NewHTTPError selects the reference error name for its built-in status codes. Set Type explicitly for application errors or validation errors.
type Handler ¶
type Handler func(*RequestContext) (any, error)
type InvalidEventError ¶
type InvalidEventError struct{}
func (*InvalidEventError) Error ¶
func (*InvalidEventError) Error() string
type InvalidHTTPMethodError ¶
type InvalidHTTPMethodError struct{ Method string }
func (*InvalidHTTPMethodError) Error ¶
func (e *InvalidHTTPMethodError) Error() string
type Middleware ¶
type Middleware func(*RequestContext, Next) error
Middleware calls next synchronously or short-circuits using RequestContext.Respond.
func CORS ¶
func CORS(options CORSOptions) Middleware
CORS sets response headers before downstream middleware and short-circuits valid OPTIONS preflight requests. Invalid preflights continue normal routing.
func Compress ¶
func Compress(options CompressionOptions) Middleware
Compress selects the configured coding using exact tokens and quality weights. An explicitly preferred identity skips compression; equal weights may compress. It does not filter content types or change status when no coding is selected. Response bodies are buffered because Resolve produces a buffered proxy result.
func Validate ¶
func Validate(config ValidationConfig) Middleware
Validate runs request checks before next and response checks after it. Transformed values live in Valid; the request and response are not rewritten.
type ParameterValidationError ¶
type ParameterValidationError struct{ Message string }
func (*ParameterValidationError) Error ¶
func (e *ParameterValidationError) Error() string
type ProxyResponse ¶
type ProxyResponse struct {
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
IsBase64Encoded bool `json:"isBase64Encoded"`
MultiValueHeaders map[string][]string `json:"multiValueHeaders,omitempty"`
Cookies []string `json:"cookies,omitempty"`
StatusDescription string `json:"statusDescription,omitempty"`
}
ProxyResponse is the Lambda integration response, shared by all event adapters.
func WebResponseToProxyResult ¶
func WebResponseToProxyResult(response *nethttp.Response, kind ResponseType, encoded bool) (ProxyResponse, error)
WebResponseToProxyResult serializes an owned response body and closes it.
type RequestChecks ¶
type RequestChecks struct{ Body, Headers, Path, Query Check }
type RequestContext ¶
type RequestContext struct {
Context context.Context
Request *nethttp.Request
Response *nethttp.Response
Event jsonv1.RawMessage
ResponseType ResponseType
Route string
Params map[string]string
Store *Store
IsBase64Encoded *bool
IsHTTPStreaming bool
Valid ValidatedData
}
RequestContext owns per-invocation state while retaining the caller's context.
func (*RequestContext) ClientIP ¶
func (r *RequestContext) ClientIP() string
ClientIP returns the event's source IP for API Gateway and Function URLs. ALB uses the first X-Forwarded-For value. This is request metadata, not a trusted authorization input; the source and forwarding headers are caller-controlled.
func (*RequestContext) Respond ¶
func (r *RequestContext) Respond(value any) error
Respond replaces the response while retaining headers already set by middleware.
type RequestConversionError ¶
type RequestConversionError struct{ Cause error }
RequestConversionError identifies conversion failures before HTTP middleware. Its cause retains the adapter's diagnostic without becoming a 500 response.
func (*RequestConversionError) Error ¶
func (e *RequestConversionError) Error() string
func (*RequestConversionError) Unwrap ¶
func (e *RequestConversionError) Unwrap() error
type Response ¶
type Response struct {
StatusCode int
Headers nethttp.Header
MultiValueHeaders nethttp.Header
Body any
Cookies []string
// Nil selects automatic encoding. True string bodies contain standard
// Base64; bytes, readers and JSON values remain raw. False selects text.
IsBase64Encoded *bool
}
Response is the Go equivalent of an extended proxy handler result. Body strings are verbatim unless marked as preencoded; other JSON values are serialized.
type ResponseChecks ¶
type ResponseChecks struct{ Body, Headers Check }
type ResponseStream ¶
type ResponseStream struct {
// contains filtered or unexported fields
}
ResponseStream is the native aws-lambda-go reader contract. Close cancels the producer and waits for its cleanup. Handlers/readers must cooperate with context cancellation; arbitrary blocking application code cannot be forcibly stopped.
func (*ResponseStream) Close ¶
func (s *ResponseStream) Close() error
func (*ResponseStream) ContentType ¶
func (s *ResponseStream) ContentType() string
func (*ResponseStream) MarshalJSON ¶
func (s *ResponseStream) MarshalJSON() ([]byte, error)
type ResponseType ¶
type ResponseType string
const ( APIGatewayV1 ResponseType = "ApiGatewayV1" APIGatewayV2 ResponseType = "ApiGatewayV2" ALB ResponseType = "ALB" )
func ProxyEventToWebRequest ¶
ProxyEventToWebRequest adapts JSON values or typed Lambda event structures.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
func (*Router) Handle ¶
func (r *Router) Handle(method, path string, handler Handler, middleware ...Middleware) error
Handle registers a string path. Dynamic parameters use :name syntax.
func (*Router) HandleRegex ¶
func (r *Router) HandleRegex(method, pattern string, handler Handler, middleware ...Middleware) error
HandleRegex registers an anchored Go regular expression after dynamic routes. Use named captures for parameters. JavaScript-only regex forms remain unsupported.
func (*Router) IncludeRouter ¶
IncludeRouter copies routes, global middleware, error handlers and shared keys. Included global middleware applies to the parent router, matching the reference.
func (*Router) MethodNotAllowed ¶
func (r *Router) MethodNotAllowed(handler ErrorHandler)
func (*Router) NotFound ¶
func (r *Router) NotFound(handler ErrorHandler)
func (*Router) OnError ¶
func (r *Router) OnError(name string, handler ErrorHandler)
OnError registers a reference error name, "HttpError", or the "Error" fallback.
func (*Router) Resolve ¶
Resolve accepts JSON values or typed Lambda events. Panics retain their identity. Conversion errors and context cancellation remain Go errors; handler errors become HTTP responses through the registered error policy.
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
httpapi "github.com/rambow-cloud/powertools-lambda-go/eventhandler/http"
)
func main() {
app := httpapi.New(httpapi.Options{})
if err := app.Get("/orders/:id", func(request *httpapi.RequestContext) (any, error) {
return httpapi.Response{StatusCode: 200, Body: request.Params["id"]}, nil
}); err != nil {
panic(err)
}
event := json.RawMessage(`{"version":"2.0","routeKey":"$default","rawPath":"/orders/order-123","rawQueryString":"","headers":{},"requestContext":{"http":{"method":"GET"},"domainName":"api.example.test"},"isBase64Encoded":false}`)
response, err := app.Resolve(context.Background(), event)
fmt.Println(response.StatusCode, response.Body, err)
}
Output: 200 order-123 <nil>
func (*Router) ResolveStream ¶
ResolveStream writes the Lambda HTTP integration metadata, eight zero bytes, then raw body bytes. It finishes copying and closing the body before returning. The caller owns the destination. Write/read errors after metadata are returned without attempting to replace the response with another HTTP error document.
func (*Router) Use ¶
func (r *Router) Use(middleware ...Middleware)
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store synchronizes its keys. Callers own synchronization of mutable values. Each invocation has a fresh Store; Router.Shared survives warm invocations.
type StreamPanicError ¶
type StreamPanicError struct{ Value any }
StreamPanicError reports a panic from the producer goroutine after synchronous middleware and observability defers have run. Value retains the original panic.
func (*StreamPanicError) Error ¶
func (e *StreamPanicError) Error() string
func (*StreamPanicError) Unwrap ¶
func (e *StreamPanicError) Unwrap() error
type ValidatedData ¶
type ValidationConfig ¶
type ValidationConfig struct {
Request *RequestChecks
Response *ResponseChecks
}
type ValidationIssue ¶
ValidationIssue retains the Standard Schema issue fields used by HTTP errors.