eventhandler

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Overview

Package eventhandler routes the HTTP requests that reach a Lambda function through Amazon API Gateway (REST and HTTP APIs), an Application Load Balancer, a Lambda Function URL or VPC Lattice: the Go side of Powertools for AWS Lambda (Python)'s REST and HTTP event handler, with its data validation, OpenAPI document and Swagger UI.

net/http at the core

A Router is an http.Handler. Routes are http.Handlers, middlewares are func(http.Handler) http.Handler, tests use net/http/httptest, and local development is http.ListenAndServe(":8080", app), Python's HttpResolverLocal for free. An adapter per event source turns the router into a Lambda handler: it builds the *http.Request from the event (method, path, query string with every value, headers, cookies, body decoded from base64, the caller's address) and the event's response from what the router wrote.

app := eventhandler.New()
app.HandleFunc("GET /todos", listTodos)
eventhandler.Get(app, "/todos/{id}", getTodo)
lambda.Start(eventhandler.APIGatewayREST(app))

Source                          Adapter          Python
API Gateway REST, HTTP API 1.0  APIGatewayREST   APIGatewayRestResolver
API Gateway HTTP API 2.0        APIGatewayHTTP   APIGatewayHttpResolver
Application Load Balancer       ALB              ALBResolver
Lambda Function URL (buffered)  FunctionURL      LambdaFunctionUrlResolver
VPC Lattice, version 1          VPCLattice       VPCLatticeResolver
VPC Lattice, version 2          VPCLatticeV2     VPCLatticeV2Resolver

The raw event is in the request context: APIGatewayRESTEvent, APIGatewayHTTPEvent, ALBEvent, FunctionURLEvent, VPCLatticeEvent and VPCLatticeV2Event return it, lambdacontext.FromContext the Lambda context. Bedrock agents are served by the bedrockagent package, on the same router.

Routing

Patterns use net/http's syntax ("GET /todos/{id}", "/files/{path...}") and Powertools' rules: a pattern matches the whole path; routes without wildcards are tried first, then the others in registration order; a method mismatch is a 404; GET does not answer HEAD; nothing redirects. Read path values with r.PathValue. HandleRegexp registers Python's regular expression routes. REST API routes ignore trailing slashes, as Python's REST resolver does. WithStripPrefixes and WithStripPrefixRegexps remove the base path of a custom domain mapping before routing. Registering the same route twice panics.

Typed operations

Register (and Get, Post, Put, Patch, Delete, Head) registers a function func(ctx, In) (Out, error): In binds path, query, header and cookie parameters, form fields and files, and the JSON body (a field named Body) from struct tags; Out is the JSON response, or a Response choosing its status, headers and cookies. Constraints in the tags of github.com/swaggest/jsonschema-go (minimum, maxLength, pattern, enum, format, required...) generate one schema per operation that validates the request, describes the operation in the OpenAPI document and, with WithResponseValidation or ResponseValidation, validates the response. The schemas compile when the operation registers, with a small validator of the JSON Schema subset the tags generate (a general engine would cost every cold start the compilation of its meta-schemas); a schema using a keyword it does not implement, which a type's own PrepareJSONSchema could add, makes Register panic. A request that does not conform answers 422 with Python's body:

{"statusCode":422,"detail":[{"loc":["query","limit"],"type":"int_parsing"}]}

and a body of an unsupported content type 415. RequestFromContext gives a typed operation the request it serves.

Errors

A typed operation fails by returning an error, a middleware or a plain handler by calling Error. A *ServiceError (BadRequest, Unauthorized, Forbidden, NotFound, RequestTimeout, RequestEntityTooLarge, InternalServerError, ServiceUnavailable) answers its status with {"statusCode":...,"message":...}. OnError registers handlers by error type (see its precedence rules), HandleNotFound the handler of unmatched requests. Any other error fails the invocation, as an exception does in Python, unless debug mode (WithDebug, POWERTOOLS_DEV) answers 500 with the error and the stack. Panics are not recovered.

Middlewares

Use adds middlewares to every request, matched or not; Middlewares adds them to one route, after the router's. A middleware short-circuits by writing a response without calling next. Include merges the routes of another router under a prefix, with its middlewares and error handlers, as Python's include_router does. The schemavalidation package validates JSON bodies against JSON Schemas with the validation package.

Responses

WithCORS answers pre-flight requests and adds the CORS headers (route option CORS turns them off or on per route); Compress gzips responses for clients that accept it; CacheControl sets Cache-Control on 200 responses and no-cache on others. Bodies that are not text (binary content types, compressed bodies) are base64-encoded for the proxy response. Cookies set with http.SetCookie travel in multiValueHeaders (REST, ALB with multi-value headers), in the cookies list (HTTP API, Function URL) or as the last Set-Cookie header (ALB single-value, VPC Lattice). ALB checks the 1 MB response limit with WithResponseSizeValidation.

OpenAPI

OpenAPI and OpenAPIJSON return the OpenAPI 3.1 document of the routes, built with github.com/swaggest/openapi-go; WithOpenAPI sets the title, version, servers, tags, security schemes and the rest, route options the summary, description, tags, operationId, security, extensions, responses. MergeOpenAPI merges the documents of several functions. The swaggerui package serves the Swagger UI.

Options

Router: WithCORS, WithStripPrefixes, WithStripPrefixRegexps, WithDebug, WithSerializer, WithDeserializer, WithResponseValidation, WithOpenAPI. Route: CORS, Compress, CacheControl, StatusCode, Middlewares, ResponseValidation, Summary, Description, Tags, OperationID, Deprecated, ExcludeFromSchema, Security, Extension, ResponseDescription, ResponseModel.

Environment variables

POWERTOOLS_DEV turns debug mode on unless WithDebug says otherwise. POWERTOOLS_DEBUG shows what the router does in the Powertools debug log.

Differences from Powertools Python

  • Handlers are net/http handlers and typed operations; there are no resolver classes per source, no current_event on the app (read it from the request context), no append_context (use context values) and no Depends: middlewares put values in the request context and handlers read them with typed getters.
  • Patterns use net/http's {name} and {name...} instead of <name>; path values are percent-decoded, Python passes them encoded.
  • Parameters are bound by struct tags instead of signature annotations; JSON bodies decode strictly ("1" is not an integer), Python coerces. Required parameters say so with required:"true"; Go has no "no default".
  • Repeated query parameters of HTTP APIs and Function URLs stay separate (the adapter reads the raw query string); Python splits single values on commas. Header list parameters split on commas for every source.
  • A typed operation's string output is a JSON string; Python sends str bodies unquoted. Use a []byte body for raw content.
  • Response validation failures are ResponseValidationErrors with the configured status, 422 by default; Python reports them as request validation errors when no status is configured.
  • Errors from middlewares and handlers are answered where they happen, so the middlewares around them see the error response; in Python the exception skips their "after" logic.
  • Router middlewares and error handlers merge on Include as in Python; a router included elsewhere keeps no options of its own.
  • ALB query strings arrive percent-encoded and are decoded by url.Values: decode_query_parameters is always on. ALB and VPC Lattice responses carry a status description. VPC Lattice responses send the last cookie as a Set-Cookie header (Python puts cookies in a field Lattice ignores).
  • Responses carry Vary: Origin when CORS allows specific origins, and Vary: Accept-Encoding on routes that compress, so that caches keep the variants apart.
  • The OpenAPI validation error schemas list statusCode and do not require msg, matching the bodies actually sent; components are named after the Go type; regular expression routes and routes without a method are not documented; bodies of GET, HEAD and DELETE operations are bound and validated but not documented.
  • A multipart body without a boundary answers 422 (multipart_invalid); Python raises an unhandled error.
  • Not ported: dependency_overrides (inject dependencies with closures or interfaces), resolve_async (handlers use goroutines), the specialized routers (one Router type serves every source), the custom JSON body deserializer for non-typed routes (handlers read r.Body).
Example
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/powertools-lambda-go/eventhandler"
)

func main() {
	app := eventhandler.New()
	app.HandleFunc("GET /hello/{name}", func(w http.ResponseWriter, r *http.Request) {
		if err := eventhandler.WriteJSON(w, r, http.StatusOK, map[string]string{"message": "hello " + r.PathValue("name")}); err != nil {
			eventhandler.Error(w, r, err)
		}
	})

	// In main: lambda.Start(eventhandler.APIGatewayREST(app))
	handler := eventhandler.APIGatewayREST(app)
	resp, err := handler(context.Background(), events.APIGatewayProxyRequest{HTTPMethod: "GET", Path: "/hello/lambda"})
	if err != nil {
		panic(err)
	}
	fmt.Println(resp.StatusCode, resp.Body)
}
Output:
200 {"message":"hello lambda"}

Index

Examples

Constants

View Source
const (
	DefaultOpenAPITitle        = "Powertools for AWS Lambda (Go) API"
	DefaultAPIVersion          = "1.0.0"
	DefaultResponseDescription = "Successful Response"
)

Defaults of the OpenAPI document, Powertools Python's with the runtime's name.

View Source
const (
	ContentTypeJSON = "application/json"
	ContentTypeText = "text/plain"
	ContentTypeHTML = "text/html"
)

Content types the event handler writes.

View Source
const ALBMaxResponseSize = 1 << 20

ALBMaxResponseSize is the largest response an Application Load Balancer accepts from a Lambda target, in bytes.

Variables

View Source
var (
	ErrBadRequest            = &ServiceError{StatusCode: http.StatusBadRequest}
	ErrUnauthorized          = &ServiceError{StatusCode: http.StatusUnauthorized}
	ErrForbidden             = &ServiceError{StatusCode: http.StatusForbidden}
	ErrNotFound              = &ServiceError{StatusCode: http.StatusNotFound}
	ErrRequestTimeout        = &ServiceError{StatusCode: http.StatusRequestTimeout}
	ErrRequestEntityTooLarge = &ServiceError{StatusCode: http.StatusRequestEntityTooLarge}
	ErrInternalServerError   = &ServiceError{StatusCode: http.StatusInternalServerError}
	ErrServiceUnavailable    = &ServiceError{StatusCode: http.StatusServiceUnavailable}
)

Sentinels for errors.Is: each matches every *ServiceError with its status.

View Source
var ErrDuplicateRoute = errors.New("duplicate route")

ErrDuplicateRoute reports a route registered twice: the same method and a path with the same shape, which the second one could never serve.

View Source
var ErrInvalidOperation = errors.New("invalid typed operation")

ErrInvalidOperation reports the input struct of a typed operation that cannot be bound: Register panics with it.

View Source
var ErrInvalidPattern = errors.New("invalid route pattern")

ErrInvalidPattern reports a route pattern that cannot be parsed.

View Source
var ErrMergeConflict = errors.New("OpenAPI merge conflict")

ErrMergeConflict reports an operation defined by several documents, with ConflictError: Python's OpenAPIMergeError.

View Source
var ErrSchemaValidation = errors.New("invalid OpenAPI configuration")

ErrSchemaValidation reports an OpenAPI configuration that cannot make a valid document: a security requirement naming an unknown scheme, an extension whose name does not start with "x-": Python's SchemaValidationError.

Functions

func ALB

ALB adapts h to an Application Load Balancer target group: Python's ALBResolver.

When the target group has multi-value headers on, the request carries every value of each header and query parameter, and so does the response; otherwise the response keeps the last value of each header and the last cookie, with a warning, as Python does. Query strings arrive percent-encoded from ALB and stay so in the URL, so the values read from it are decoded: Python's decode_query_parameters is always on.

func ALBEvent

ALBEvent returns the Application Load Balancer event the request was built from.

func APIGatewayHTTP

APIGatewayHTTP adapts h to an API Gateway HTTP API with payload format 2.0: Python's APIGatewayHttpResolver.

The path is the raw path without the stage prefix (unless the stage is $default), the query is the raw query string, so repeated parameters stay separate, and the cookies list becomes the Cookie header. The response joins header values with ", " and moves Set-Cookie headers to cookies.

func APIGatewayHTTPEvent

func APIGatewayHTTPEvent(ctx context.Context) (events.APIGatewayV2HTTPRequest, bool)

APIGatewayHTTPEvent returns the API Gateway HTTP API (payload 2.0) event the request was built from.

func APIGatewayREST

APIGatewayREST adapts h to an API Gateway REST API proxy integration (and to an HTTP API with payload format 1.0): Python's APIGatewayRestResolver.

The request carries the event's method, path, query string (every value of the multi-value map), headers, cookies, body (base64-decoded) and the caller's source IP as RemoteAddr; routes ignore trailing slashes, as in Python. The response puts every header, Set-Cookie included, in multiValueHeaders, and base64-encodes bodies that are not text, which needs binary media types configured on the API.

func APIGatewayRESTEvent

func APIGatewayRESTEvent(ctx context.Context) (events.APIGatewayProxyRequest, bool)

APIGatewayRESTEvent returns the API Gateway REST API (or HTTP API payload 1.0) event the request was built from: Python's current_event.

func BasePath

func BasePath(ctx context.Context) string

BasePath returns the path prefix under which the client called the API: "/{stage}" for an API Gateway stage URL ("" for the $default stage, a custom domain or SAM local), "" for the other sources. The Swagger UI uses it for the server of its "Try it out" requests.

func Delete

func Delete[In, Out any](r *Router, path string, op func(ctx context.Context, in In) (Out, error), opts ...RouteOption)

Delete registers a typed DELETE operation for path; see Register.

func Error

func Error(w http.ResponseWriter, r *http.Request, err error)

Error answers the request with err, as raising it does in Python: through the error handlers of the router serving r (see OnError), else with the built-in response of a *ServiceError, a *RequestValidationError, a *ResponseValidationError or an *UnsupportedContentTypeError. Any other error is unhandled: the Lambda invocation fails with it (in debug mode, the response is a 500 with the error and the stack), and a local server answers 500. The status and the body the handler had written are discarded; the headers the middlewares set stay.

Middlewares and plain handlers call Error to fail a request the way a typed operation does by returning an error.

func FunctionURL

FunctionURL adapts h to a Lambda Function URL in BUFFERED invoke mode: Python's LambdaFunctionUrlResolver. Requests and responses are those of APIGatewayHTTP. For RESPONSE_STREAM mode, serve the router with aws-lambda-go's lambdaurl.Start instead, which streams what it writes.

func FunctionURLEvent

func FunctionURLEvent(ctx context.Context) (events.LambdaFunctionURLRequest, bool)

FunctionURLEvent returns the Lambda Function URL event the request was built from.

func Get

func Get[In, Out any](r *Router, path string, op func(ctx context.Context, in In) (Out, error), opts ...RouteOption)

Get registers a typed GET operation for path; see Register.

Example
package main

import (
	"context"
	"fmt"

	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/powertools-lambda-go/eventhandler"
)

type Todo struct {
	ID    int    `json:"id"`
	Title string `json:"title" required:"true" minLength:"1"`
}

type GetTodo struct {
	ID     int    `path:"id" minimum:"1"`
	Fields string `query:"fields" enum:"all,title" default:"all"`
}

func main() {
	app := eventhandler.New()
	eventhandler.Get(app, "/todos/{id}", func(_ context.Context, in GetTodo) (Todo, error) {
		if in.ID == 42 {
			return Todo{}, eventhandler.NotFound("todo 42 not found")
		}
		return Todo{ID: in.ID, Title: "Buy milk"}, nil
	})

	handler := eventhandler.APIGatewayHTTP(app)
	for _, path := range []string{"/todos/1", "/todos/0", "/todos/42"} {
		resp, err := handler(context.Background(), events.APIGatewayV2HTTPRequest{
			RawPath:        path,
			RequestContext: events.APIGatewayV2HTTPRequestContext{HTTP: events.APIGatewayV2HTTPRequestContextHTTPDescription{Method: "GET"}},
		})
		if err != nil {
			panic(err)
		}
		fmt.Println(resp.StatusCode, resp.Body)
	}
}
Output:
200 {"id":1,"title":"Buy milk"}
422 {"statusCode":422,"detail":[{"loc":["path","id"],"type":"greater_than_equal"}]}
404 {"statusCode":404,"message":"todo 42 not found"}
func Head[In, Out any](r *Router, path string, op func(ctx context.Context, in In) (Out, error), opts ...RouteOption)

Head registers a typed HEAD operation for path; see Register.

func MergeOpenAPI

func MergeOpenAPI(cfg OpenAPIConfig, onConflict ConflictStrategy, docs ...[]byte) ([]byte, error)

MergeOpenAPI merges the OpenAPI documents of several functions into one, for an API whose routes live in separate Lambda functions: Python's OpenAPIMerge. cfg gives the document-level fields; the paths, components and tags come from docs (each an OpenAPI JSON document, such as Router.OpenAPIJSON writes). Components of the same name are replaced by the later document's, as in Python; tags of cfg come first.

Python discovers the handlers by scanning source files; a Go function's routes live in its binary, so each function writes its document at build time (or exports a function that registers its routes, for a program that imports them all) and the documents are merged here.

Example
package main

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/alessandrolattao/powertools-lambda-go/eventhandler"
)

func main() {
	orders := eventhandler.New()
	orders.HandleFunc("GET /orders", func(http.ResponseWriter, *http.Request) {})
	users := eventhandler.New()
	users.HandleFunc("GET /users", func(http.ResponseWriter, *http.Request) {})

	ordersDoc, err := orders.OpenAPIJSON()
	if err != nil {
		panic(err)
	}
	usersDoc, err := users.OpenAPIJSON()
	if err != nil {
		panic(err)
	}
	merged, err := eventhandler.MergeOpenAPI(eventhandler.OpenAPIConfig{Title: "Shop"}, eventhandler.ConflictError, ordersDoc, usersDoc)
	if err != nil {
		panic(err)
	}
	fmt.Println(strings.Contains(string(merged), `"/orders"`), strings.Contains(string(merged), `"/users"`))
}
Output:
true true

func OnError

func OnError[E error](r *Router, fn func(w http.ResponseWriter, r *http.Request, err E) error)

OnError registers fn as the handler of the errors of type E: Python's exception_handler. When a typed operation, a middleware or a handler (through Error) fails with an error, the router looks for a handler:

  1. a 404 *ServiceError goes to the HandleNotFound handler, if any;
  2. walking the error tree from the outermost error (Unwrap, depth first), the first error whose concrete type has a handler wins;
  3. otherwise the handlers of interface types, in registration order, the first one errors.As matches; a handler for error itself, Python's handler for Exception, comes last.

fn writes the response. If it returns an error instead, that error gets the built-in response (a *ServiceError, a validation error) or fails the invocation. Registering a type again replaces its handler.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"

	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/powertools-lambda-go/eventhandler"
)

var errOutOfStock = errors.New("out of stock")

func main() {
	app := eventhandler.New()
	eventhandler.OnError(app, func(w http.ResponseWriter, r *http.Request, err error) error {
		if errors.Is(err, errOutOfStock) {
			return eventhandler.WriteJSON(w, r, http.StatusConflict, map[string]string{"error": err.Error()})
		}
		return err // the built-in response, or a failed invocation
	})
	eventhandler.Post(app, "/orders", func(context.Context, struct{}) (string, error) {
		return "", fmt.Errorf("order 1: %w", errOutOfStock)
	})

	resp, err := eventhandler.ALB(app)(context.Background(), events.ALBTargetGroupRequest{HTTPMethod: "POST", Path: "/orders"})
	if err != nil {
		panic(err)
	}
	fmt.Println(resp.StatusCode, resp.Body)
}
Output:
409 {"error":"order 1: out of stock"}

func Patch

func Patch[In, Out any](r *Router, path string, op func(ctx context.Context, in In) (Out, error), opts ...RouteOption)

Patch registers a typed PATCH operation for path; see Register.

func Post

func Post[In, Out any](r *Router, path string, op func(ctx context.Context, in In) (Out, error), opts ...RouteOption)

Post registers a typed POST operation for path; see Register.

Example
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/powertools-lambda-go/eventhandler"
)

type Todo struct {
	ID    int    `json:"id"`
	Title string `json:"title" required:"true" minLength:"1"`
}

type CreateTodo struct {
	Body Todo
}

func main() {
	app := eventhandler.New()
	eventhandler.Post(app, "/todos", func(_ context.Context, in CreateTodo) (eventhandler.Response[Todo], error) {
		in.Body.ID = 7
		return eventhandler.Response[Todo]{
			StatusCode: http.StatusCreated,
			Header:     http.Header{"Location": {"/todos/7"}},
			Body:       in.Body,
		}, nil
	}, eventhandler.StatusCode(http.StatusCreated))

	resp, err := eventhandler.APIGatewayREST(app)(context.Background(), events.APIGatewayProxyRequest{
		HTTPMethod: "POST", Path: "/todos", Body: `{"title":"Write docs"}`,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(resp.StatusCode, resp.MultiValueHeaders["Location"], resp.Body)
}
Output:
201 [/todos/7] {"id":7,"title":"Write docs"}

func Put

func Put[In, Out any](r *Router, path string, op func(ctx context.Context, in In) (Out, error), opts ...RouteOption)

Put registers a typed PUT operation for path; see Register.

func Register

func Register[In, Out any](r *Router, pattern string, op func(ctx context.Context, in In) (Out, error), opts ...RouteOption)

Register registers a typed operation for pattern, which must name a method ("GET /todos/{id}"): the handler receives its input bound from the request into In and returns the Out written as the response, the Go side of Python's routes with data validation.

In is a struct whose fields say where their values come from:

type GetTodo struct {
	ID      int    `path:"id" minimum:"1"`
	Fields  string `query:"fields" enum:"all,title"`
	TraceID string `header:"X-Trace-Id"`
	Session string `cookie:"session"`
}

A field named Body is the request body, decoded from JSON (a []byte Body takes the raw body of any content type). Fields tagged formData:"name" are form fields of an application/x-www-form-urlencoded or multipart/form-data body; a *multipart.FileHeader (or a slice of them) is an uploaded file. Embedded structs contribute their fields. Fields without one of these tags or names are left alone.

Values are converted to the field's type: strings, booleans, integers, floats, types implementing encoding.TextUnmarshaler (time.Time), pointers to them (nil when absent) and slices of them (every value of a repeated parameter; header values split on commas). Constraints use the tags of github.com/swaggest/jsonschema-go: required, minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, minLength, maxLength, pattern, enum, format, minItems, maxItems, default, description, example, deprecated. Path parameters are always required.

The same schemas validate the request, describe the operation in the OpenAPI document and, when enabled, validate the response, so the three cannot drift. A request that does not conform answers 422 with Python's body; a body of a content type the operation does not read answers 415.

Out is written as JSON with the route's status (200 unless StatusCode says otherwise), or as a Response when the operation picks its own status, headers and cookies. An error from op is answered through the error handlers (see OnError); an error none handles fails the invocation, as an exception does in Python.

The schemas compile here, once: Register panics when the pattern is invalid or has no method, when In is not a struct or binds a field of a type it cannot convert, when the path parameters of the pattern and of In differ, or when a schema uses a JSON Schema keyword or format the built-in validator does not enforce (see docs/eventhandler-openapi.md), which only a type's own schema methods can add.

func RegisterRegexp

func RegisterRegexp[In, Out any](r *Router, method string, re *regexp.Regexp, op func(ctx context.Context, in In) (Out, error), opts ...RouteOption)

RegisterRegexp registers a typed operation for a regular expression route: see Register and Router.HandleRegexp. The named groups of re are the path parameters.

func RequestFromContext

func RequestFromContext(ctx context.Context) (*http.Request, bool)

RequestFromContext returns the request a router is serving with ctx, the context of the request or one derived from it (the context a typed operation receives). It is how a typed operation reads what its input struct does not bind, as Python's Request parameter does.

func VPCLattice

VPCLattice adapts h to a VPC Lattice target group with event structure version 1: Python's VPCLatticeResolver. Repeated query parameters arrive folded with commas: list parameters of typed operations split them.

func VPCLatticeEvent

func VPCLatticeEvent(ctx context.Context) (eventsource.VPCLatticeEvent, bool)

VPCLatticeEvent returns the VPC Lattice (version 1) event the request was built from.

func VPCLatticeV2

VPCLatticeV2 adapts h to a VPC Lattice target group with event structure version 2, the one AWS recommends: Python's VPCLatticeV2Resolver. Headers and query parameters keep all their values.

func VPCLatticeV2Event

func VPCLatticeV2Event(ctx context.Context) (eventsource.VPCLatticeEventV2, bool)

VPCLatticeV2Event returns the VPC Lattice version 2 event the request was built from.

func WriteJSON

func WriteJSON(w http.ResponseWriter, r *http.Request, status int, v any) error

WriteJSON writes v as a JSON response with status, encoded with the serializer of the router serving r (see WithSerializer), the way the router writes its own JSON responses.

Types

type ALBOption

type ALBOption func(*albConfig)

ALBOption configures the ALB adapter.

func WithResponseSizeValidation

func WithResponseSizeValidation() ALBOption

WithResponseSizeValidation checks the size of the serialized response against ALB's 1 MB limit, Python's enable_response_size_validation: a bigger response is a *ResponseSizeExceededError, which an error handler registered on the router (see OnError) can turn into a smaller response; that response is checked again, and the invocation fails when it is still too big or nobody handled the error.

type CORSConfig

type CORSConfig struct {
	// AllowOrigin is the origin allowed to call the API; "*", the default,
	// allows any and should only be used while prototyping.
	AllowOrigin string
	// ExtraOrigins are further allowed origins.
	ExtraOrigins []string
	// AllowHeaders are allowed request headers, on top of Authorization,
	// Content-Type, X-Amz-Date, X-Api-Key and X-Amz-Security-Token.
	AllowHeaders []string
	// ExposeHeaders are the response headers the browser may read
	// (Access-Control-Expose-Headers).
	ExposeHeaders []string
	// MaxAge is how many seconds a pre-flight response may be cached
	// (Access-Control-Max-Age); nil sends no header.
	MaxAge *int
	// AllowCredentials sends Access-Control-Allow-Credentials: true when
	// the allowed origin is not "*".
	AllowCredentials bool
}

CORSConfig is the Cross-Origin Resource Sharing configuration of a router: Python's CORSConfig, with its defaults.

type ConflictStrategy

type ConflictStrategy int

ConflictStrategy says what MergeOpenAPI does when several documents define the same operation (method and path): Python's on_conflict.

const (
	// ConflictWarn keeps the first definition and logs a warning, the
	// default.
	ConflictWarn ConflictStrategy = iota
	// ConflictError fails the merge with ErrMergeConflict.
	ConflictError
	// ConflictFirst keeps the first definition silently.
	ConflictFirst
	// ConflictLast keeps the last definition.
	ConflictLast
)

The conflict strategies.

type Contact

type Contact struct {
	Name  string
	URL   string
	Email string
}

Contact is the contact information of the API.

type ExternalDocs

type ExternalDocs struct {
	Description string
	URL         string
}

ExternalDocs links to documentation elsewhere.

type License

type License struct {
	Name string
	// Identifier is an SPDX expression (OpenAPI 3.1 only).
	Identifier string
	URL        string
}

License is the license of the API.

type Middleware

type Middleware = func(next http.Handler) http.Handler

Middleware wraps an http.Handler, net/http's middleware shape. It runs before the handler when it calls next, after it when next returns, and short-circuits the request when it writes a response without calling next.

type OAuthFlow

type OAuthFlow struct {
	AuthorizationURL string
	TokenURL         string
	RefreshURL       string
	// Scopes maps scope names to their descriptions.
	Scopes map[string]string
}

OAuthFlow is one OAuth2 flow.

type OAuthFlows

type OAuthFlows struct {
	Implicit          *OAuthFlow
	Password          *OAuthFlow
	ClientCredentials *OAuthFlow
	AuthorizationCode *OAuthFlow
}

OAuthFlows are the flows of an OAuth2 security scheme.

type OpenAPIConfig

type OpenAPIConfig struct {
	// Title defaults to DefaultOpenAPITitle.
	Title string
	// Version is the version of the API, DefaultAPIVersion by default.
	Version string
	// Summary is a short summary of the API (OpenAPI 3.1 only).
	Summary string
	// Description is a longer description, in Markdown.
	Description    string
	TermsOfService string
	Contact        *Contact
	License        *License
	// Servers defaults to a single server at "/".
	Servers []Server
	Tags    []Tag
	// SecuritySchemes declares the security schemes, by name.
	SecuritySchemes map[string]SecurityScheme
	// Security applies security requirements to every operation.
	Security     []SecurityRequirement
	ExternalDocs *ExternalDocs
	// Extensions are "x-" fields of the document.
	Extensions map[string]any
}

OpenAPIConfig holds the document-level fields of the OpenAPI document: Python's OpenAPIConfig.

type OpenAPIOption

type OpenAPIOption func(*OpenAPIConfig)

OpenAPIOption adjusts the configuration of one document, over the router's WithOpenAPI.

type Option

type Option func(*config)

Option configures a Router made with New. Options matter only on the router that serves requests: a router included in another one brings its routes, middlewares and error handlers, not its options.

func WithCORS

func WithCORS(cfg CORSConfig) Option

WithCORS enables CORS on every route, unless a route opts out with CORS(false), and answers pre-flight requests: Python's cors parameter.

Example
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/powertools-lambda-go/eventhandler"
)

type Todo struct {
	ID    int    `json:"id"`
	Title string `json:"title" required:"true" minLength:"1"`
}

func main() {
	app := eventhandler.New(eventhandler.WithCORS(eventhandler.CORSConfig{
		AllowOrigin:   "https://www.example.com",
		ExposeHeaders: []string{"X-Request-Id"},
	}))
	app.HandleFunc("GET /todos", func(w http.ResponseWriter, r *http.Request) {
		if err := eventhandler.WriteJSON(w, r, http.StatusOK, []Todo{}); err != nil {
			eventhandler.Error(w, r, err)
		}
	})

	handler := eventhandler.APIGatewayREST(app)
	preflight, err := handler(context.Background(), events.APIGatewayProxyRequest{
		HTTPMethod: "OPTIONS", Path: "/todos",
		Headers: map[string]string{"Origin": "https://www.example.com"},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(preflight.StatusCode, preflight.MultiValueHeaders["Access-Control-Allow-Methods"],
		preflight.MultiValueHeaders["Access-Control-Allow-Origin"])
}
Output:
204 [GET,OPTIONS] [https://www.example.com]

func WithDebug

func WithDebug(enabled bool) Option

WithDebug turns the debug mode on or off. It defaults to POWERTOOLS_DEV. In debug mode an unhandled error answers 500 with the error and the stack as text instead of failing the invocation, and the router writes what it does to the Powertools debug log (shown with POWERTOOLS_DEBUG).

func WithDeserializer

func WithDeserializer(unmarshal func(data []byte, v any) error) Option

WithDeserializer replaces the JSON decoder of the request bodies of typed operations: Python's json_body_deserializer. The default is encoding/json/v2's Unmarshal, accepting duplicate names as Python does.

func WithOpenAPI

func WithOpenAPI(cfg OpenAPIConfig) Option

WithOpenAPI sets the document-level fields of the OpenAPI document: Python's configure_openapi.

func WithResponseValidation

func WithResponseValidation(status int) Option

WithResponseValidation validates what every typed operation returns against its response schema, and answers with status when it does not conform: Python's response_validation_error_http_code. A route can choose its own status with ResponseValidation.

func WithSerializer

func WithSerializer(marshal func(v any) ([]byte, error)) Option

WithSerializer replaces the JSON encoder of response bodies: Python's serializer. The default is encoding/json/v2's Marshal, compact, with map keys sorted as encoding/json sorts them.

func WithStripPrefixRegexps

func WithStripPrefixRegexps(prefixes ...*regexp.Regexp) Option

WithStripPrefixRegexps removes every match of each expression from the request path before routing, as Python's strip_prefixes does with compiled patterns ("/v[1-3]+/(dev|stg)"): unlike a string prefix, a regular expression does not stop the stripping.

func WithStripPrefixes

func WithStripPrefixes(prefixes ...string) Option

WithStripPrefixes removes the first of the prefixes the request path starts with before routing, as Python's strip_prefixes does with strings: a path equal to a prefix becomes "/", "/payment/todos" becomes "/todos" for the prefix "/payment". It serves APIs mapped under a base path of a custom domain. Prefixes apply in the order the options give them.

type RequestValidationError

type RequestValidationError struct {
	Errors []ValidationErrorDetail
	// Body is the request body.
	Body []byte
}

RequestValidationError reports a request that does not match the input of its typed operation. It answers 422 with {"statusCode":422,"detail":[{"loc":[...],"type":"..."}]} unless an error handler takes it.

func (*RequestValidationError) Error

func (e *RequestValidationError) Error() string

type Response

type Response[T any] struct {
	// StatusCode is the status; zero means the route's (see StatusCode).
	StatusCode int
	// Header holds response headers.
	Header http.Header
	// Cookies are sent with Set-Cookie. Unlike Python's Cookie, Go's
	// http.Cookie is not Secure unless asked.
	Cookies []*http.Cookie
	// Body is the response body.
	Body T
	// Compress, when set, decides the compression of this response over the
	// route's Compress option (the client must still accept gzip).
	Compress *bool
}

Response is what a typed operation returns when the status, the headers or the cookies are its own to choose: Python's Response. Body is written as JSON (unless T is []byte, written as it is) with Content-Type application/json unless Header sets another; the OpenAPI document and response validation describe T.

type ResponseSizeExceededError

type ResponseSizeExceededError struct {
	ActualSize int
	MaxSize    int
}

ResponseSizeExceededError reports a response bigger than its event source allows (1 MB for ALB, see WithResponseSizeValidation).

func (*ResponseSizeExceededError) Error

func (e *ResponseSizeExceededError) Error() string

type ResponseValidationError

type ResponseValidationError struct {
	Errors []ValidationErrorDetail
	// StatusCode is the status the route or the router chose.
	StatusCode int
	// Body is the response that failed.
	Body any
}

ResponseValidationError reports a response of a typed operation that does not match its schema, when response validation is on. It answers StatusCode with the body of RequestValidationError.

func (*ResponseValidationError) Error

func (e *ResponseValidationError) Error() string

type RouteInfo

type RouteInfo struct {
	Method      string
	Path        string
	Pattern     string
	Summary     string
	Description string
	// Security reports whether the route sets security requirements.
	Security bool
}

RouteInfo describes a documented route.

type RouteOption

type RouteOption func(*routeConfig)

RouteOption configures one route.

func CORS

func CORS(enabled bool) RouteOption

CORS turns CORS on or off for the route, whatever the router does. A route that turns it on in a router without WithCORS uses CORSConfig's defaults.

func CacheControl

func CacheControl(value string) RouteOption

CacheControl sets the Cache-Control header of 200 responses to value; other statuses get "no-cache".

func Compress

func Compress() RouteOption

Compress gzips the response when the request accepts gzip.

func Deprecated

func Deprecated() RouteOption

Deprecated marks the operation as deprecated in the OpenAPI document.

func Description

func Description(description string) RouteOption

Description sets the description of the operation in the OpenAPI document; Bedrock agents require one.

func ExcludeFromSchema

func ExcludeFromSchema() RouteOption

ExcludeFromSchema leaves the route out of the OpenAPI document: Python's include_in_schema=False.

func Extension

func Extension(name string, value any) RouteOption

Extension adds an OpenAPI extension to the operation; name must start with "x-".

func Middlewares

func Middlewares(middlewares ...Middleware) RouteOption

Middlewares adds middlewares to the route. They run after the router's own, in order.

func OperationID

func OperationID(id string) RouteOption

OperationID sets the operationId. It defaults to the handler's function name, the path and the method, as Python generates it.

func ResponseDescription

func ResponseDescription(description string) RouteOption

ResponseDescription sets the description of the successful response in the OpenAPI document. It defaults to "Successful Response".

func ResponseModel

func ResponseModel(status int, description string, model any) RouteOption

ResponseModel documents a response of the operation: its status, its description and the Go value its JSON body looks like (a nil model means the operation's own response type). As in Python, routes that document their responses this way replace the default successful response.

func ResponseValidation

func ResponseValidation(status int) RouteOption

ResponseValidation validates the responses of the typed operation and answers status when one does not conform, whatever WithResponseValidation says: Python's custom_response_validation_http_code.

func Security

func Security(requirements ...SecurityRequirement) RouteOption

Security sets the security requirements of the operation, by the names of the security schemes of the OpenAPI configuration. An empty requirement makes security optional. Powertools documents security; it does not enforce it.

func StatusCode

func StatusCode(status int) RouteOption

StatusCode sets the status of the successful responses of a typed operation, and the status the OpenAPI document gives them. It defaults to 200.

func Summary

func Summary(summary string) RouteOption

Summary sets the summary of the operation in the OpenAPI document. It defaults to the method and the path.

func Tags

func Tags(tags ...string) RouteOption

Tags groups the operation under tags in the OpenAPI document.

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router routes HTTP requests with Powertools' rules and serves them through middlewares, error handlers, CORS and compression. It is an http.Handler: the event source adapters (APIGatewayREST, APIGatewayHTTP, ALB, FunctionURL, VPCLattice, VPCLatticeV2) turn it into a Lambda handler, and http.ListenAndServe serves it locally.

Register routes, middlewares and error handlers before serving: a Router is safe for concurrent requests, not for registrations during them.

func New

func New(opts ...Option) *Router

New returns an empty Router.

func (*Router) Handle

func (r *Router) Handle(pattern string, h http.Handler, opts ...RouteOption)

Handle registers h for the requests matching pattern.

A pattern is net/http's "[METHOD ]/path": "GET /todos/{id}" matches one path segment into the path value id (read it with r.PathValue), "/files/{path...}" matches the rest of the path. Matching follows Powertools rather than http.ServeMux: a pattern matches the whole path (a trailing slash is not a subtree, "{$}" is accepted and changes nothing), patterns without wildcards are tried first and then the others in registration order, a method mismatch is a 404 (no 405), GET does not serve HEAD, and nothing redirects. A pattern without a method matches every method. Registering the same method and path shape twice panics with ErrDuplicateRoute, as a conflict does in http.ServeMux.

func (*Router) HandleFunc

func (r *Router) HandleFunc(pattern string, h func(http.ResponseWriter, *http.Request), opts ...RouteOption)

HandleFunc registers the handler function h for pattern; see Handle.

func (*Router) HandleNotFound

func (r *Router) HandleNotFound(h http.Handler)

HandleNotFound sets the handler of the requests no route matches, and of the errors that are a *ServiceError with status 404: Python's not_found. It runs through the router's middlewares. Without it, such requests get a 404 {"statusCode":404,"message":"Not found"}.

func (*Router) HandleRegexp

func (r *Router) HandleRegexp(method string, re *regexp.Regexp, h http.Handler, opts ...RouteOption)

HandleRegexp registers h for the requests whose method is method (any method when empty) and whose whole path matches re, as Powertools Python's regular expression rules do. The named groups of re are the path values. A route whose expression has groups counts as having wildcards; without, it is tried with the literal routes. Regular expression routes are not part of the OpenAPI document, which cannot describe them.

func (*Router) Include

func (r *Router) Include(sub *Router, prefix string)

Include adds the routes of sub to r, under prefix ("" for none): Python's include_router. A "/" route of sub becomes the prefix itself. As in Python, the middlewares of sub join r's (they then run for every route of r, after the middlewares r had when Include was called), and the error handlers of sub replace r's for the same error types. Include copies what sub has at the time of the call.

Example
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/powertools-lambda-go/eventhandler"
)

func main() {
	answer := func(w http.ResponseWriter, r *http.Request) {
		if err := eventhandler.WriteJSON(w, r, http.StatusOK, map[string]string{"id": r.PathValue("id")}); err != nil {
			eventhandler.Error(w, r, err)
		}
	}
	todos := eventhandler.New()
	todos.HandleFunc("GET /", answer)
	todos.HandleFunc("GET /{id}", answer)

	app := eventhandler.New()
	app.Include(todos, "/todos")

	handler := eventhandler.APIGatewayREST(app)
	for _, path := range []string{"/todos", "/todos/3"} {
		resp, err := handler(context.Background(), events.APIGatewayProxyRequest{HTTPMethod: "GET", Path: path})
		if err != nil {
			panic(err)
		}
		fmt.Println(resp.Body)
	}
}
Output:
{"id":""}
{"id":"3"}

func (*Router) OpenAPI

func (r *Router) OpenAPI(opts ...OpenAPIOption) (*openapi31.Spec, error)

OpenAPI returns the OpenAPI 3.1 document of the router's routes: Python's get_openapi_schema. Typed operations are described from their input and output types; plain handlers by their path parameters and their options.

func (*Router) OpenAPI30JSON

func (r *Router) OpenAPI30JSON(opts ...OpenAPIOption) ([]byte, error)

OpenAPI30JSON returns the router's document in OpenAPI 3.0.3, the version Amazon Bedrock agents read (see the bedrockagent package), as indented JSON.

func (*Router) OpenAPIJSON

func (r *Router) OpenAPIJSON(opts ...OpenAPIOption) ([]byte, error)

OpenAPIJSON returns the OpenAPI 3.1 document as indented JSON: Python's get_openapi_json_schema, what the Swagger UI serves and what a build step writes to openapi.json.

Example
package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/alessandrolattao/powertools-lambda-go/eventhandler"
)

type Todo struct {
	ID    int    `json:"id"`
	Title string `json:"title" required:"true" minLength:"1"`
}

type GetTodo struct {
	ID     int    `path:"id" minimum:"1"`
	Fields string `query:"fields" enum:"all,title" default:"all"`
}

func main() {
	app := eventhandler.New(eventhandler.WithOpenAPI(eventhandler.OpenAPIConfig{Title: "Todos", Version: "1.2.0"}))
	eventhandler.Get(app, "/todos/{id}", func(context.Context, GetTodo) (Todo, error) { return Todo{}, nil },
		eventhandler.Summary("Get a todo"), eventhandler.Tags("todos"))

	doc, err := app.OpenAPIJSON()
	if err != nil {
		panic(err)
	}
	fmt.Println(strings.Contains(string(doc), `"summary": "Get a todo"`), strings.Contains(string(doc), `"$ref": "#/components/schemas/Todo"`))
}
Output:
true true

func (*Router) Routes

func (r *Router) Routes() []RouteInfo

Routes lists the documented operations of the router, for checks such as the description Bedrock agents require.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP routes req and writes the response.

func (*Router) Use

func (r *Router) Use(middlewares ...Middleware)

Use adds middlewares that run for every request, matched or not (including pre-flight and not found responses), in order and before the middlewares of the route: Python's use.

Example
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/aws/aws-lambda-go/events"

	"github.com/alessandrolattao/powertools-lambda-go/eventhandler"
)

func main() {
	app := eventhandler.New()
	app.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.Header.Get("Authorization") == "" {
				eventhandler.Error(w, r, eventhandler.Unauthorized("Unauthorized"))
				return
			}
			next.ServeHTTP(w, r)
		})
	})
	app.HandleFunc("GET /secret", func(w http.ResponseWriter, r *http.Request) {
		if err := eventhandler.WriteJSON(w, r, http.StatusOK, "s3cr3t"); err != nil {
			eventhandler.Error(w, r, err)
		}
	})

	resp, err := eventhandler.FunctionURL(app)(context.Background(), events.LambdaFunctionURLRequest{
		RawPath:        "/secret",
		RequestContext: events.LambdaFunctionURLRequestContext{HTTP: events.LambdaFunctionURLRequestContextHTTPDescription{Method: "GET"}},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(resp.StatusCode, resp.Body)
}
Output:
401 {"statusCode":401,"message":"Unauthorized"}

type SecurityRequirement

type SecurityRequirement map[string][]string

SecurityRequirement maps security scheme names to the scopes required; several schemes in one requirement are all required.

type SecurityScheme

type SecurityScheme struct {
	// Type is "apiKey", "http", "oauth2", "openIdConnect" or "mutualTLS".
	Type        string
	Description string
	// Name and In locate an API key ("query", "header" or "cookie").
	Name string
	In   string
	// Scheme and BearerFormat describe HTTP authentication.
	Scheme       string
	BearerFormat string
	// Flows are the OAuth2 flows.
	Flows            *OAuthFlows
	OpenIDConnectURL string
	Extensions       map[string]any
}

SecurityScheme is a security scheme of the OpenAPI document. The constructors below build each kind, as Python's models do.

func APIKeyScheme

func APIKeyScheme(name, in string) SecurityScheme

APIKeyScheme is an API key passed in a header, a query parameter or a cookie: Python's APIKey.

func HTTPBearerScheme

func HTTPBearerScheme(bearerFormat string) SecurityScheme

HTTPBearerScheme is bearer token authentication: Python's HTTPBearer.

func HTTPScheme

func HTTPScheme(scheme string) SecurityScheme

HTTPScheme is an HTTP authentication scheme ("basic"...): Python's HTTPBase.

func MutualTLSScheme

func MutualTLSScheme() SecurityScheme

MutualTLSScheme is mutual TLS (OpenAPI 3.1 only): Python's MutualTLS.

func OAuth2Scheme

func OAuth2Scheme(flows OAuthFlows) SecurityScheme

OAuth2Scheme is OAuth2 with the given flows: Python's OAuth2.

func OpenIDConnectScheme

func OpenIDConnectScheme(url string) SecurityScheme

OpenIDConnectScheme is OpenID Connect discovery: Python's OpenIdConnect.

type Server

type Server struct {
	URL         string
	Description string
	Variables   map[string]ServerVariable
	Extensions  map[string]any
}

Server is a server of the API.

type ServerVariable

type ServerVariable struct {
	Enum        []string
	Default     string
	Description string
}

ServerVariable is a variable of a server URL template.

type ServiceError

type ServiceError struct {
	StatusCode int
	// Message is a string, or any value that encodes to JSON.
	Message any
}

ServiceError is an error that is an HTTP response: the status and the message of the body {"statusCode": ..., "message": ...}. Return it from a typed operation, or pass it to Error, to answer with it: Python's ServiceError and its subclasses (BadRequestError, NotFoundError...), which the constructors below build.

func BadRequest

func BadRequest(message string) *ServiceError

BadRequest is a 400 error: Python's BadRequestError.

func Forbidden

func Forbidden(message string) *ServiceError

Forbidden is a 403 error: Python's ForbiddenError.

func InternalServerError

func InternalServerError(message string) *ServiceError

InternalServerError is a 500 error: Python's InternalServerError.

func NewServiceError

func NewServiceError(status int, message any) *ServiceError

NewServiceError returns a ServiceError with status and message.

func NotFound

func NotFound(message string) *ServiceError

NotFound is a 404 error: Python's NotFoundError. An empty message is "Not found", Python's default.

func RequestEntityTooLarge

func RequestEntityTooLarge(message string) *ServiceError

RequestEntityTooLarge is a 413 error: Python's RequestEntityTooLargeError.

func RequestTimeout

func RequestTimeout(message string) *ServiceError

RequestTimeout is a 408 error: Python's RequestTimeoutError.

func ServiceUnavailable

func ServiceUnavailable(message string) *ServiceError

ServiceUnavailable is a 503 error: Python's ServiceUnavailableError.

func Unauthorized

func Unauthorized(message string) *ServiceError

Unauthorized is a 401 error: Python's UnauthorizedError.

func (*ServiceError) Error

func (e *ServiceError) Error() string

func (*ServiceError) Is

func (e *ServiceError) Is(target error) bool

Is reports whether target is a *ServiceError with the same status, so that errors.Is(err, ErrNotFound) matches every 404.

type Tag

type Tag struct {
	Name         string
	Description  string
	ExternalDocs *ExternalDocs
}

Tag describes a tag the operations use.

type UnsupportedContentTypeError

type UnsupportedContentTypeError struct {
	ContentType string
}

UnsupportedContentTypeError reports a request body whose content type the typed operation does not read. It answers 415 with {"statusCode":415,"detail":[{"loc":["body"],"type":"unsupported_content_type"}]}.

func (*UnsupportedContentTypeError) Error

type VPCLatticeResponse

type VPCLatticeResponse struct {
	StatusCode        int               `json:"statusCode"`
	StatusDescription string            `json:"statusDescription,omitempty"`
	Headers           map[string]string `json:"headers,omitempty"`
	Body              string            `json:"body"`
	IsBase64Encoded   bool              `json:"isBase64Encoded"`
}

VPCLatticeResponse is the response of a function behind a VPC Lattice target group, for both event structure versions.

type ValidationErrorDetail

type ValidationErrorDetail struct {
	// Loc locates the failure: where ("path", "query", "header",
	// "cookie", "body", "response"), then the name, then the field path,
	// with array indexes as ints.
	Loc []any `json:"loc"`
	// Type is the error code, Pydantic's: "missing", "int_parsing",
	// "string_too_short", "json_invalid"...
	Type string `json:"type"`
	// Msg explains the failure.
	Msg string `json:"-"`
	// Input is the value that failed, when there is one.
	Input any `json:"-"`
}

ValidationErrorDetail is one failure of a request or a response to its schema. Only Loc and Type reach the client, as in Python, which hides the rest "for security reasons"; Msg and Input are for logs.

Directories

Path Synopsis
Package appsync routes the invocations of AWS AppSync GraphQL direct Lambda resolvers (and of the Amplify GraphQL Transformer @function directive) to typed Go resolvers, one per type and field.
Package appsync routes the invocations of AWS AppSync GraphQL direct Lambda resolvers (and of the Amplify GraphQL Transformer @function directive) to typed Go resolvers, one per type and field.
Package appsyncevents handles the publish and subscribe operations of AWS AppSync Events channel namespaces whose handler is a Lambda function, routing each to the Go handler registered for its channel path.
Package appsyncevents handles the publish and subscribe operations of AWS AppSync Events channel namespaces whose handler is a Lambda function, routing each to the Go handler registered for its channel path.
Package bedrockagent serves the action groups of Amazon Bedrock agents: the Go side of Powertools for AWS Lambda (Python)'s BedrockAgentResolver and BedrockAgentFunctionResolver.
Package bedrockagent serves the action groups of Amazon Bedrock agents: the Go side of Powertools for AWS Lambda (Python)'s BedrockAgentResolver and BedrockAgentFunctionResolver.
examples
openapimerge command
Command openapimerge writes the OpenAPI document of an API whose routes live in two Lambda functions, the Go side of Powertools Python's OpenAPIMerge.
Command openapimerge writes the OpenAPI document of an API whose routes live in two Lambda functions, the Go side of Powertools Python's OpenAPIMerge.
internal
lambdahttp
Package lambdahttp carries an HTTP request built from a Lambda event through an http.Handler and collects the response, for the event source adapters of the eventhandler packages.
Package lambdahttp carries an HTTP request built from a Lambda event through an http.Handler and collects the response, for the event source adapters of the eventhandler packages.
schema
Package schema validates JSON values against the JSON Schema documents the typed operations of the event handler generate from struct tags (through github.com/swaggest/jsonschema-go): a deliberately small JSON Schema 2020-12 validator.
Package schema validates JSON values against the JSON Schema documents the typed operations of the event handler generate from struct tags (through github.com/swaggest/jsonschema-go): a deliberately small JSON Schema 2020-12 validator.
schema/schematest
Package schematest generates JSON Schema documents of the subset the schema package implements, and JSON instances, from fuzzer bytes, so that tests can compare the validator with a reference implementation.
Package schematest generates JSON Schema documents of the subset the schema package implements, and JSON instances, from fuzzer bytes, so that tests can compare the validator with a reference implementation.
Package schemavalidation validates the JSON bodies of the requests and responses of an eventhandler.Router against JSON Schemas, with the validation package: Powertools for AWS Lambda (Python)'s SchemaValidationMiddleware.
Package schemavalidation validates the JSON bodies of the requests and responses of an eventhandler.Router against JSON Schemas, with the validation package: Powertools for AWS Lambda (Python)'s SchemaValidationMiddleware.
Package swaggerui serves the Swagger UI of an eventhandler.Router's OpenAPI document: Powertools for AWS Lambda (Python)'s enable_swagger.
Package swaggerui serves the Swagger UI of an eventhandler.Router's OpenAPI document: Powertools for AWS Lambda (Python)'s enable_swagger.

Jump to

Keyboard shortcuts

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