lambda

package module
v0.4.5 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 19 Imported by: 2

README

Lambda handler wrappers with sensible defaults

Go Reference

Convenient handler wrappers

The various StartABC functions wrap your Lambda handler so that a Metrics instance (from github.com/nguyengg/go-aws-commons/metrics) is available from context and will be logged with sensible default metrics (start and end time, latency, fault, etc.) upon return of your Lambda handler.

package main

import (
	"context"

	"github.com/aws/aws-lambda-go/events"
	"github.com/nguyengg/go-aws-commons/lambda"
	"github.com/nguyengg/go-aws-commons/metrics"
)

func main() {
	// start Lambda loop like this.
	lambda.StartHandlerFunc(func(ctx context.Context, event events.DynamoDBEvent) (events.DynamoDBEventResponse, error) {
		m := metrics.Get(ctx)
		m.AddCounter("userDidSomethingCool", 1)

		// when your handler returns, the Metrics instance will be logged to standard error stream.
		// see https://pkg.go.dev/github.com/nguyengg/go-aws-commons/metrics for examples of what is logged.
		return events.DynamoDBEventResponse{}, nil
	})
}


Gin adapter for Function URL

A Gin adapter for API Gateway V1 and V2 are already available from github.com/awslabs/aws-lambda-go-api-proxy. The gin-function-url module (named ginadapter) provides an adapter specifically for Function URL events with both BUFFERED (which, technically, is no different from API Gateway V2/HTTP events) and RESPONSE_STREAM mode which uses github.com/aws/aws-lambda-go/lambdaurl.

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/render"
	functionurl "github.com/nguyengg/go-aws-commons/lambda/function-url"
)

func main() {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {
		c.Render(http.StatusOK, render.String{
			Format: "hello, world!",
		})
	})

	// start the Lambda handler either in BUFFERED or STREAM_RESPONSE mode.
	functionurl.StartBuffered(r)
	functionurl.StartStream(r)
}

GetParameter and GetSecretValue using AWS Parameter and Secrets Lambda extension

When running in Lambda, if you need to retrieve parameters from Parameter Store or secrets from Secrets Manager, you can use the AWS Parameter and Secrets Lambda extension to cache the values. The extension was first described in detail in blog post https://aws.amazon.com/blogs/compute/using-the-aws-parameter-and-secrets-lambda-extension-to-cache-parameters-and-secrets/.

package main

import (
	"context"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
	"github.com/aws/aws-sdk-go-v2/service/ssm"
	"github.com/nguyengg/go-aws-commons/lambda"
)

func main() {
	// lambda.ParameterSecretsExtensionClient implements GetSecretValue and GetParameter so I can substitute the
	// client to any code that needs it. the zero-value struct is ready for use.
	c := lambda.ParameterSecretsExtensionClient{}

	// in my Lambda handler, instead of invoking Secrets Manager SDK directly, I can use the client from the
	// extension package which makes use of the AWS Parameter and Secrets Lambda extension.
	_, err := c.GetSecretValue(context.Background(), &secretsmanager.GetSecretValueInput{
		SecretId:     aws.String("my-secret"),
		VersionId:    nil,
		VersionStage: nil,
	})

	// I can also use the package-level methods which will use the default client.
	_, err = lambda.GetParameter(context.Background(), &ssm.GetParameterInput{
		Name:           aws.String("my-parameter"),
		WithDecryption: nil,
	})
}

getenv adds abstraction on top of this so that I can easily swap out how the variable is retrieved.

package main

import (
	"context"
	"crypto/hmac"
	"crypto/sha256"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
	"github.com/aws/aws-sdk-go-v2/service/ssm"
	"github.com/nguyengg/go-aws-commons/lambda/getenv"
)

func main() {
	// while prototyping, you can retrieve from environment variable
	v := getenv.Env("TEST")

	// now you want to retrieve from Parameter Store instead
	v = getenv.ParameterString(&ssm.GetParameterInput{
		Name:           aws.String("my-parameter-name"),
		WithDecryption: aws.Bool(true),
	})

	// in the next example, the key is retrieved and then used as secret key for HMAC verification.
	key := getenv.SecretBinary(&secretsmanager.GetSecretValueInput{
		SecretId:     aws.String("my-secret-id"),
		VersionId:    nil,
		VersionStage: nil,
	})
	h := hmac.New(sha256.New, key.MustGetWithContext(context.Background()))
	h.Write( /* some data */ )
	h.Sum(nil)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultParameterSecretsExtensionClient = &ParameterSecretsExtensionClient{Client: http.DefaultClient}

DefaultParameterSecretsExtensionClient is the client used by package-level GetSecretValue and GetParameter.

Functions

func GetParameter

func GetParameter(ctx context.Context, input *ssm.GetParameterInput) (*ssm.GetParameterOutput, error)

GetParameter is a wrapper around [DefaultClient.GetParameter].

func GetSecretValue

GetSecretValue is a wrapper around [DefaultClient.GetSecretValue].

func SetUpSlogDefault added in v0.4.0

func SetUpSlogDefault()

SetUpSlogDefault sets the default slog.Default to print JSON messages to os.Stderr, respecting AWS_LAMBDA_LOG_FORMAT and AWS_LAMBDA_LOG_LEVEL if given.

Replicates the logic of lambdacontext.NewLogHandler with a few key differences:

  • "awsRequestId" is used instead of "requestId".
  • defaults to JSON handler if AWS_LAMBDA_LOG_FORMAT is not given.
  • if DEBUG environment variable is true-ish, override AWS_LAMBDA_LOG_LEVEL to DEBUG.

func Start added in v0.1.1

func Start[TIn any, H ConsumerFunc[TIn]](handler H, options ...awslambda.Option)

Start is a variant of StartHandlerFunc for handlers that don't have any explicit returned value.

See StartHandlerFunc for details.

func StartDynamodbEventHandler added in v0.4.3

func StartDynamodbEventHandler(handler func(context.Context, events.DynamoDBEventRecord) error, options ...lambda.Option)

StartDynamodbEventHandler starts the Lambda loop for handling DynamoDB stream events in a batch.

See https://docs.aws.amazon.com/lambda/latest/dg/services-ddb-batchfailurereporting.html.

The handler works on one record at a time and sequentially. If the handler returns a non-nil error, the wrapper will automatically add an events.DynamoDBBatchItemFailure so that only failed records get retried later.

func StartHandlerFunc added in v0.1.1

func StartHandlerFunc[TIn any, TOut any, H awslambda.HandlerFunc[TIn, TOut]](handler H, options ...awslambda.Option)

StartHandlerFunc is a wrapper around lambda.StartHandlerFunc that adds sensible logging and metrics out of the box.

A metrics.Metrics instance will be made available via context by way of metrics.Get. The "fault" and "panicked" counters will be populated accordingly: if the handler returns a non-nil error, "fault" will be set to 1, and "error" property to the error; if the handler panics, "panicked" will be set to 1, "error" to the recovered error, and "stack" to the stack trace.

See SetUpLogDefault and SetUpSlogDefault for how the default loggers are configured. Additionally, for each Lambda invocation, the AWS request Id will also be attached to log.Default as the message prefix, slog.Default as the attribute "awsRequestId". To disable this feature, specify either HandlerFuncOptions.NoSetUpLogging or ConsumerFuncOptions.NoSetUpLogging.

If you need to customise the metrics.Metrics instance, use NewHandlerFunc.

func StartSQSMessageHandler added in v0.2.1

func StartSQSMessageHandler(handler func(context.Context, events.SQSMessage) error, options ...lambda.Option)

StartSQSMessageHandler starts the Lambda loop for handling SQS messages in a batch.

See https://docs.aws.amazon.com/prescriptive-guidance/latest/lambda-event-filtering-partial-batch-responses-for-sqs/benefits-partial-batch-responses.html for why partial batch response is preferable over failing the entire batch.

The handler works on one message at a time and sequentially. If the handler returns a non-nil error, the wrapper will automatically add an events.SQSBatchItemFailure so that only failed messages get retried later.

func StreamToDynamoDBAttributeValue added in v0.4.3

func StreamToDynamoDBAttributeValue(av events.DynamoDBAttributeValue) dynamodbtypes.AttributeValue

StreamToDynamoDBAttributeValue converts a DynamoDB Stream event attribute value (from https://pkg.go.dev/github.com/aws/aws-lambda-go/events) to an equivalent DynamoDB attribute value (from https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb/types).

See StreamToDynamoDBItem for usage.

func StreamToDynamoDBItem added in v0.4.3

func StreamToDynamoDBItem(in map[string]events.DynamoDBAttributeValue) map[string]dynamodbtypes.AttributeValue

StreamToDynamoDBItem uses StreamToDynamoDBAttributeValue to convert an item from a DynamoDB Stream event to an item in DynamoDB.

Useful if you're implementing a DynamoDB Stream event handler, and you need to convert the old and/or new image to the tagged struct by way of https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue:

item := &MyStruct{}
err := attributevalue.UnmarshalMap(StreamToDynamoDBItem(record.Change.NewImage), item)

Types

type ConsumerFunc added in v0.3.0

type ConsumerFunc[TIn any] interface {
	func(context.Context, TIn) error
}

ConsumerFunc is a variant of lambda.HandlerFunc that has no output (except for error).

type ConsumerFuncOptions added in v0.3.0

type ConsumerFuncOptions[TIn any, H ConsumerFunc[TIn]] struct {
	// NoSetUpLogging will disable logging features.
	NoSetUpLogging bool
	// contains filtered or unexported fields
}

ConsumerFuncOptions is returned by NewConsumerFunc to allow further customisation.

func NewConsumerFunc added in v0.3.0

func NewConsumerFunc[TIn any, H ConsumerFunc[TIn]](handler H, options ...lambda.Option) *ConsumerFuncOptions[TIn, H]

NewConsumerFunc is a more customisable variant of Start.

You must eventually call ConsumerFuncOptions.Start to enter the Lambda loop.

func (*ConsumerFuncOptions[TIn, H]) Start added in v0.3.0

func (h *ConsumerFuncOptions[TIn, H]) Start()

Start is a variant of StartHandlerFunc for handlers that don't have any explicit returned value.

See package-level StartHandlerFunc for details.

func (*ConsumerFuncOptions[TIn, H]) WithMetricsOptions added in v0.3.0

func (h *ConsumerFuncOptions[TIn, H]) WithMetricsOptions(optFns ...func(m *metrics.Metrics)) *ConsumerFuncOptions[TIn, H]

WithMetricsOptions replaces the customisations for metrics.New.

type GetParameterClient

type GetParameterClient interface {
	GetParameter(ctx context.Context, params *ssm.GetParameterInput, optFns ...func(*ssm.Options)) (*ssm.GetParameterOutput, error)
}

GetParameterClient abstracts the GetParameter API that has an implementation using AWS Parameter and Secrets Lambda extension (ParameterSecretsExtensionClient).

type GetSecretValueClient

type GetSecretValueClient interface {
	GetSecretValue(ctx context.Context, params *secretsmanager.GetSecretValueInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.GetSecretValueOutput, error)
}

GetSecretValueClient abstracts the GetSecretValue API that has an implementation using AWS Parameter and Secrets Lambda extension (ParameterSecretsExtensionClient).

type HandlerFuncOptions added in v0.3.0

type HandlerFuncOptions[TIn any, TOut any, H lambda.HandlerFunc[TIn, TOut]] struct {
	// NoSetUpLogging will disable logging features.
	NoSetUpLogging bool
	// contains filtered or unexported fields
}

HandlerFuncOptions is returned by NewHandlerFunc to allow further customisation.

func NewHandlerFunc added in v0.3.0

func NewHandlerFunc[TIn any, TOut any, H lambda.HandlerFunc[TIn, TOut]](handler H, options ...lambda.Option) *HandlerFuncOptions[TIn, TOut, H]

NewHandlerFunc is a more customisable variant of StartHandlerFunc.

You must eventually call HandlerFuncOptions.Start to enter the Lambda loop.

func (*HandlerFuncOptions[TIn, TOut, H]) Start added in v0.3.0

func (h *HandlerFuncOptions[TIn, TOut, H]) Start()

Start is a wrapper around lambda.StartHandlerFunc that adds sensible logging and metrics out of the box.

See package-level Start for details.

func (*HandlerFuncOptions[TIn, TOut, H]) WithMetricsOptions added in v0.3.0

func (h *HandlerFuncOptions[TIn, TOut, H]) WithMetricsOptions(optFns ...func(m *metrics.Metrics)) *HandlerFuncOptions[TIn, TOut, H]

WithMetricsOptions replaces the customisations for metrics.New.

type ParameterSecretsExtensionClient

type ParameterSecretsExtensionClient struct {
	// Client is the HTTP client to use for making HTTP requests.
	//
	// If nil, http.DefaultClient is used.
	Client *http.Client
	// contains filtered or unexported fields
}

ParameterSecretsExtensionClient implements both GetParameterClient and GetSecretValueClient using the AWS Parameter and Secrets Lambda extension.

See https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets_lambda.html and https://docs.aws.amazon.com/systems-manager/latest/userguide/ps-integration-lambda-extensions.html.

The zero-value DefaultParameterSecretsExtensionClient is ready for use.

func (*ParameterSecretsExtensionClient) GetParameter

func (*ParameterSecretsExtensionClient) GetSecretValue

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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