http

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 24 Imported by: 2

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func HandlerResultToWebResponse

func HandlerResultToWebResponse(value any) (*nethttp.Response, error)

HandlerResultToWebResponse converts a handler result with the default 200 status.

func IsALBEvent

func IsALBEvent(value any) bool

func IsAPIGatewayProxyEventV1

func IsAPIGatewayProxyEventV1(value any) bool

func IsAPIGatewayProxyEventV2

func IsAPIGatewayProxyEventV2(value any) bool

func IsExtendedAPIGatewayProxyResult

func IsExtendedAPIGatewayProxyResult(value any) bool

func IsHTTPMethod

func IsHTTPMethod(method string) bool

func Streamify

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

type Check func(context.Context, any) (any, []ValidationIssue, error)

Check adapts Parser, Validation or application schemas without a module dependency. Nonempty issues reject a value; operational errors remain distinct.

type CompressionOptions

type CompressionOptions struct {
	Encoding  string
	Threshold *float64
}

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

func NewHTTPError(status int, message string) *HTTPError

NewHTTPError selects the reference error name for its built-in status codes. Set Type explicitly for application errors or validation errors.

func (*HTTPError) Error

func (e *HTTPError) Error() string

func (*HTTPError) Unwrap

func (e *HTTPError) Unwrap() error

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 Next

type Next func() error

type Options

type Options struct {
	Prefix     string
	Debug      *bool
	Diagnostic func(level, message string)
}

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
	Shared          *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)

func (*ResponseStream) Read

func (s *ResponseStream) Read(p []byte) (int, error)

type ResponseType

type ResponseType string
const (
	APIGatewayV1 ResponseType = "ApiGatewayV1"
	APIGatewayV2 ResponseType = "ApiGatewayV2"
	ALB          ResponseType = "ALB"
)

func ProxyEventToWebRequest

func ProxyEventToWebRequest(ctx context.Context, event any) (*nethttp.Request, ResponseType, error)

ProxyEventToWebRequest adapts JSON values or typed Lambda event structures.

type Router

type Router struct {
	Shared *Store
	// contains filtered or unexported fields
}

func New

func New(options Options) *Router

func (*Router) Delete

func (r *Router) Delete(path string, h Handler, m ...Middleware) error

func (*Router) Get

func (r *Router) Get(path string, h Handler, m ...Middleware) error

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

func (r *Router) Head(path string, h Handler, m ...Middleware) error

func (*Router) IncludeRouter

func (r *Router) IncludeRouter(child *Router, prefix string) error

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

func (r *Router) Options(path string, h Handler, m ...Middleware) error

func (*Router) Patch

func (r *Router) Patch(path string, h Handler, m ...Middleware) error

func (*Router) Post

func (r *Router) Post(path string, h Handler, m ...Middleware) error

func (*Router) Put

func (r *Router) Put(path string, h Handler, m ...Middleware) error

func (*Router) Resolve

func (r *Router) Resolve(ctx context.Context, event any) (ProxyResponse, error)

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

func (r *Router) ResolveStream(ctx context.Context, event any, destination io.Writer) error

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.

func (*Store) Delete

func (s *Store) Delete(key string) bool

func (*Store) Entries

func (s *Store) Entries() map[string]any

func (*Store) Get

func (s *Store) Get(key string) (any, bool)

func (*Store) Has

func (s *Store) Has(key string) bool

func (*Store) Set

func (s *Store) Set(key string, value any)

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 ValidatedData struct{ Request, Response map[string]any }

type ValidationConfig

type ValidationConfig struct {
	Request  *RequestChecks
	Response *ResponseChecks
}

type ValidationIssue

type ValidationIssue struct {
	Message string `json:"message"`
	Path    []any  `json:"path,omitempty"`
}

ValidationIssue retains the Standard Schema issue fields used by HTTP errors.

Directories

Path Synopsis
metrics module
tracer module

Jump to

Keyboard shortcuts

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