Documentation
¶
Overview ¶
Package lambada provides a compatibility layer allowing to implement AWS API Gateway V1 and V2 (HTTP APIs) Lambda integrations using http.Handler. All libraries and frameworks using net/http should work using lambada.
Example:
package main
import (
"net/http"
"github.com/morelj/lambada"
)
func main() {
lambada.Serve(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write(([]byte)("<html><body><h1>Hello, World!</h1></body></html>"))
}))
}
Index ¶
- func DefaultGetRequestAttrs(req *Request, summary bool) []slog.Attr
- func DefaultGetResponseAttrs(res *Response) []slog.Attr
- func FullGetRequestAttrs(req *Request, summary bool) []slog.Attr
- func FullGetResponseAttrs(res *Response) []slog.Attr
- func IsLambda() bool
- func Serve(h http.Handler)
- func ServeWithOptions(h http.Handler, options ...Option)
- func SetBinary(w http.ResponseWriter)
- func SetOutputMode(w http.ResponseWriter, outputMode OutputMode)
- func SetText(w http.ResponseWriter)
- func WithRequest(ctx context.Context, req *Request) context.Context
- type Authorizer
- type IAMAuthorizer
- type JWTAuthorizer
- type LambadaHandler
- type Logger
- type NullLogger
- type Option
- type OutputMode
- type Request
- type RequestContext
- type Response
- type ResponseWriter
- func (w *ResponseWriter) AllowBinaryDetection()
- func (w *ResponseWriter) Body() []byte
- func (w *ResponseWriter) Header() http.Header
- func (w *ResponseWriter) SetBinary(binary bool)
- func (w *ResponseWriter) SetOutputMode(outputMode OutputMode)
- func (w *ResponseWriter) StatusCode() int
- func (w *ResponseWriter) Write(data []byte) (int, error)
- func (w *ResponseWriter) WriteHeader(statusCode int)
- type SlogLogger
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultGetRequestAttrs ¶ added in v0.3.0
DefaultGetRequestAttrs extracts default structured logging attributes from a Lambda request. The summary parameter indicates whether this is for a summary log entry (excludes some verbose fields).
func DefaultGetResponseAttrs ¶ added in v0.3.0
DefaultGetResponseAttrs extracts default structured logging attributes from a Lambda response.
func FullGetRequestAttrs ¶ added in v0.3.1
FullGetRequestAttrs extracts default structured logging attributes from a Lambda request. The summary parameter indicates whether this is for a summary log entry (excludes some verbose fields). FullGetRequestAttrs is similar to DefaultGetRequestAttrs, the difference being that the request body is included when summary is false.
func FullGetResponseAttrs ¶ added in v0.3.1
FullGetResponseAttrs extracts default structured logging attributes from a Lambda response. FullGetResponseAttrs is similar to DefaultGetResponseAttrs, the difference being that the response body is always included.
func IsLambda ¶
func IsLambda() bool
IsLambda returns whether or not the code is running in a Lambda environment. This is done by checking if the environment variable AWS_LAMBDA_FUNCTION_NAME is set.
func Serve ¶
Serve starts the Lambda handler using the http.Handler to serve incoming requests. Serve calls lambda.Start(NewHandler(h)) under the hood.
func ServeWithOptions ¶ added in v0.2.0
ServeWithOptions starts the lambda handler using the http.Handler and options to serve incoming requests. ServeWithOptions calls lambda.Start(NewHandler(h, options...)) under the hood.
func SetBinary ¶
func SetBinary(w http.ResponseWriter)
SetBinary enforces binary mode for the given ResponseWriter. That is, the response will be encoded to Base64 when returned to API Gateway.
If the passed ResponseWriter has not been provided by Lambada, this function has no effect.
func SetOutputMode ¶ added in v0.2.0
func SetOutputMode(w http.ResponseWriter, outputMode OutputMode)
SetOutputMode sets the given output mode to the given ResponseWriter.
func SetText ¶
func SetText(w http.ResponseWriter)
SetText enforces text mode for the given ResponseWriter. That is, the response will be be set to not be encoded to Base64 when returned to API Gateway.
If the passed ResponseWriter has not been provided by Lambada, this function has no effect.
func WithRequest ¶
WithRequest returns a new context.Context with the given Request attached. The returned context should then be attached to an http.Request.
There's usually no need to call this function directly, as all the work is done by lambada itself. However, it may be useful for testing purposes.
Types ¶
type Authorizer ¶ added in v0.1.3
type Authorizer struct {
IAM *IAMAuthorizer `json:"iam,omitempty"`
JWT *JWTAuthorizer `json:"jwt,omitempty"`
}
Authorizer contains authorizer details
type IAMAuthorizer ¶ added in v0.1.3
type IAMAuthorizer struct {
AccessKey string `json:"accessKey,omitempty"`
AccountID string `json:"accountId,omitempty"`
CallerID string `json:"callerId,omitempty"`
PrincipalOrgID string `json:"principalOrgId,omitempty"`
UserARN string `json:"userArn,omitempty"`
UserID string `json:"userId,omitempty"`
}
IAMAuthorizer contains the details of a request authenticated using the AWS SignV4 authorizer.
type JWTAuthorizer ¶ added in v0.1.3
type JWTAuthorizer struct {
Claims jwtclaims.Claims `json:"claims,omitempty"`
Scopes any `json:"scopes,omitempty"`
}
JWTAuthorizer contains the details of a request authenticated using the JWT authorizer.
type LambadaHandler ¶ added in v0.2.0
LambadaHandler is a Lambada lambda handler function which can be used with lambda.Start.
func NewHandler ¶ added in v0.2.0
func NewHandler(h http.Handler, options ...Option) LambadaHandler
NewHandler returns a Lambda function handler which can be used with lambda.Start. The returned lambda handler wraps incoming requets into http.Request, calls the provided http.Handler and converts the response into an API Gateway response.
type Logger ¶ added in v0.2.0
type Logger interface {
// LogRequest logs an incoming Lambda request.
LogRequest(ctx context.Context, req *Request)
// LogResponse logs the response generated for a request.
LogResponse(ctx context.Context, req *Request, res *Response)
// LogError logs an error that occurred during request processing.
LogError(ctx context.Context, req *Request, err error)
// LogPanic logs a panic that occurred during request processing.
LogPanic(ctx context.Context, req *Request, v any)
}
Logger is the interface used by Lambada to log requests, responses, errors, and panics. Implementations should handle logging asynchronously if needed to avoid blocking request processing.
type NullLogger ¶ added in v0.2.0
type NullLogger struct{}
NullLogger is a no-op Logger implementation that discards all log messages. This is the default logger used by Lambada when no logger is specified.
func (NullLogger) LogError ¶ added in v0.3.0
func (l NullLogger) LogError(context.Context, *Request, error)
LogError implements the Logger interface by doing nothing.
func (NullLogger) LogPanic ¶ added in v0.3.0
func (l NullLogger) LogPanic(context.Context, *Request, any)
LogPanic implements the Logger interface by doing nothing.
func (NullLogger) LogRequest ¶ added in v0.3.0
func (l NullLogger) LogRequest(context.Context, *Request)
LogRequest implements the Logger interface by doing nothing.
func (NullLogger) LogResponse ¶ added in v0.3.0
func (l NullLogger) LogResponse(context.Context, *Request, *Response)
LogResponse implements the Logger interface by doing nothing.
type Option ¶ added in v0.2.0
type Option func(*options)
An Option used to customize the handler behavior
func WithDefaultBinary ¶ added in v0.2.0
WithDefaultBinary enables or disable the default binary mode.
func WithLogger ¶ added in v0.2.0
WithLogger sets the handler's logger. The logger will be used to log requests, responses, errors, and panics.
func WithOutputMode ¶ added in v0.2.0
func WithOutputMode(outputMode OutputMode) Option
WithOutputMode sets the handler's output mode. OutputMode may be one of Manual, AutoContentType or Automatic.
type OutputMode ¶ added in v0.2.0
type OutputMode int8
OutputMode represents the way the request's output will be handled. See the defined OutputMode constant to get details on available output modes and how they work.
const ( // Fully manual mode. Neither Content-Type or binary mode will be automatically activated on the responses. // Binary mode may be manually set on the response writer if needed. Manual OutputMode = -1 // The Content-Type will automatically be set in the response, if not already provided. // The binary mode will not be activated automatically and must be set manually when required. // // This is the default mode for backward compatibility reasons. AutoContentType OutputMode = 0 // Fully automatic mode: The Content-Type will be set in the response, if not already provided. // If the Content-Type indicated binary data, binary mode is also activated automatically. // Binary mode can still be forcefully manually enabled, but cannot be forced to disabled. Automatic OutputMode = 1 )
type Request ¶
type Request struct {
// V1 only
Resource string `json:"resource"` // V1 - The resource path defined in API Gateway
Path string `json:"path"` // V1 - The url path for the caller
HTTPMethod string `json:"httpMethod"` // V1
MultiValueHeaders map[string][]string `json:"multiValueHeaders"` // V1
MultiValueQueryStringParameters map[string][]string `json:"multiValueQueryStringParameters"` // V1
// V2 only
Version string `json:"version"` // V2
RouteKey string `json:"routeKey"` // V2
RawPath string `json:"rawPath"` // V2
RawQueryString string `json:"rawQueryString"` // V2
Cookies []string `json:"cookies,omitempty"` // V2
// V1+V2
Headers map[string]string `json:"headers"` // V1+V2
QueryStringParameters map[string]string `json:"queryStringParameters,omitempty"` // V1+V2
PathParameters map[string]string `json:"pathParameters,omitempty"` // V1+V2
StageVariables map[string]string `json:"stageVariables,omitempty"` // V1+V2
Body string `json:"body,omitempty"` // V1+V2
IsBase64Encoded bool `json:"isBase64Encoded,omitempty"` // V1+V2
RequestContext RequestContext `json:"requestContext"` // V1+V2
// contains filtered or unexported fields
}
Request represents an API Gateway event. This struct is both compatible with V1 (Lambda Proxy Integration) and V2 (HTTP API) events and is basically a merge of the `APIGatewayProxyRequest` and `APIGatewayV2HTTPRequest` structs defined in the `github.com/aws/aws-lambda-go/events` package.
func GetRequest ¶
GetRequest returns the original API Gateway request which issued the http.Request. The returned Request value contains both API Gateway V1 and V2 data, but the used fields depend on the actual API Gateway version used.
When no API Gateway request is attached to the http.Request, this function returns nil.
func GetRequestFromContext ¶ added in v0.2.1
GetRequestFromContext returns the original API Gateway request stored in ctx. The returned Request value contains both API Gateway V1 and V2 data, but the used fields depend on the actual API Gateway version used.
When no API Gateway request is attached to the http.Request, this function returns nil.
func (*Request) VersionNumber ¶ added in v0.3.0
VersionNumber returns the version number of the request (1 or 2)
type RequestContext ¶
type RequestContext struct {
// V1 Only
ResourceID string `json:"resourceId"`
OperationName string `json:"operationName,omitempty"`
Protocol string `json:"protocol"`
Identity events.APIGatewayRequestIdentity `json:"identity"`
ResourcePath string `json:"resourcePath"`
HTTPMethod string `json:"httpMethod"`
RequestTime string `json:"requestTime"`
RequestTimeEpoch int64 `json:"requestTimeEpoch"`
// V2 Only
RouteKey string `json:"routeKey"`
Time string `json:"time"`
TimeEpoch int64 `json:"timeEpoch"`
HTTP events.APIGatewayV2HTTPRequestContextHTTPDescription `json:"http"`
// V1 + V2
AccountID string `json:"accountId"`
Stage string `json:"stage"`
DomainName string `json:"domainName"`
DomainPrefix string `json:"domainPrefix"`
RequestID string `json:"requestId"`
APIID string `json:"apiId"` // The API Gateway rest API Id
Authorizer *Authorizer `json:"authorizer,omitempty"`
}
RequestContext contains the information to identify the AWS account and resources invoking the Lambda function. This struct is both compatible with V1 (Lambda Proxy Integration) and V2 (HTTP API) events and is basically a merge of the `APIGatewayProxyRequestContext` and `APIGatewayV2HTTPRequestContext` structs defined in the `github.com/aws/aws-lambda-go/events` package.
type Response ¶
type Response struct {
Cookies []string `json:"cookies,omitempty"` // V2
StatusCode int `json:"statusCode"` // V1+V2
Headers map[string]string `json:"headers"` // V1+V2
MultiValueHeaders map[string][]string `json:"multiValueHeaders"` // V1+V2
Body string `json:"body"` // V1+V2
IsBase64Encoded bool `json:"isBase64Encoded,omitempty"` // V1+V2
}
Response contains the response to send back to API Gateway This struct is both compatible with V1 (Lambda Proxy Integration) and V2 (HTTP API) events and is basically a merge of the `APIGatewayProxyResponse` and `APIGatewayV2HTTPResponse` structs defined in the `github.com/aws/aws-lambda-go/events` package.
type ResponseWriter ¶ added in v0.1.2
type ResponseWriter struct {
// contains filtered or unexported fields
}
ResponseWriter is an implementation of http.ResponseWriter which stores the data written to it internally. Trailers are not supported by this implementation.
You usually access ResponseWriter through the http.ResponseWriter interface. If you need to access the underlying ResponseWriter use:
// w is an http.ResponseWriter rw, ok := w.(*lambada.ResponseWriter)
func (*ResponseWriter) AllowBinaryDetection ¶ added in v0.2.0
func (w *ResponseWriter) AllowBinaryDetection()
AllowBinaryDetection allows binary detection to happen on w. Automatic binary detection will only happen when the OutputMode is set to Automatic.
func (*ResponseWriter) Body ¶ added in v0.1.2
func (w *ResponseWriter) Body() []byte
Body returns the current body's byte. If nothing has been written, Body returns nil. The returned slice is valid until the next call to Write.
func (*ResponseWriter) Header ¶ added in v0.1.2
func (w *ResponseWriter) Header() http.Header
Header returns the response's header set. Once the WriteHeader has been called, Header returns a new copy of the response's headers, preventing them from being modified.
func (*ResponseWriter) SetBinary ¶ added in v0.1.2
func (w *ResponseWriter) SetBinary(binary bool)
SetBinary sets whether or not the binary mode should be enabled or not. When binary mode is enabled, the response is encoded to Base64 before being returned to API Gateway. The mode set through this function is forced - meaning that automatic binary detection will be skipped. Use AllowBinaryDetection() to revert this behavior.
func (*ResponseWriter) SetOutputMode ¶ added in v0.2.0
func (w *ResponseWriter) SetOutputMode(outputMode OutputMode)
SetOutputMode sets the output mode for w.
func (*ResponseWriter) StatusCode ¶ added in v0.1.2
func (w *ResponseWriter) StatusCode() int
StatusCode returns w's current status code. If WriteHeaders() has not been called yet, returns 200.
func (*ResponseWriter) Write ¶ added in v0.1.2
func (w *ResponseWriter) Write(data []byte) (int, error)
Write writes data to the response body buffer. If WriteHeader has not been called, Write calls WriteHeader(http.StatusOK) before writing the data.
func (*ResponseWriter) WriteHeader ¶ added in v0.1.2
func (w *ResponseWriter) WriteHeader(statusCode int)
WriteHeader sends an HTTP response header with the provided status code. If WriteHeader is called more than once, only the first call takes effect. The status code must be between 100 and 599, otherwise WriteHeader panics.
type SlogLogger ¶ added in v0.3.0
type SlogLogger struct {
// Logger is the underlying slog.Logger used for actual logging.
Logger *slog.Logger
// Level is the log the level to use for requests and responses
Level slog.Level
// GetRequestAttrs is an optional function to extract custom attributes from requests.
// If nil, DefaultGetRequestAttrs is used. The summary parameter indicates whether
// this is for a summary log (true) or a detailed log (false).
GetRequestAttrs func(req *Request, summary bool) []slog.Attr
// GetResponseAttrs is an optional function to extract custom attributes from responses.
// If nil, DefaultGetResponseAttrs is used.
GetResponseAttrs func(res *Response) []slog.Attr
}
SlogLogger is a Logger implementation that uses Go's structured logging (slog) package. It provides structured logging with customizable attribute extraction functions.
func (*SlogLogger) LogError ¶ added in v0.3.0
func (l *SlogLogger) LogError(ctx context.Context, req *Request, err error)
LogError logs an error that occurred during request processing at Error level.
func (*SlogLogger) LogPanic ¶ added in v0.3.0
func (l *SlogLogger) LogPanic(ctx context.Context, req *Request, v any)
LogPanic logs a panic that occurred during request processing at Error level.
func (*SlogLogger) LogRequest ¶ added in v0.3.0
func (l *SlogLogger) LogRequest(ctx context.Context, req *Request)
LogRequest logs an incoming Lambda request at Info level with structured attributes.
func (*SlogLogger) LogResponse ¶ added in v0.3.0
func (l *SlogLogger) LogResponse(ctx context.Context, req *Request, res *Response)
LogResponse logs a Lambda response at Info level with both request and response attributes.