Define Lambda function handlers in Go
The Lambda function handler is the method in your function code that processes events. When your function is invoked, Lambda runs the handler method. Your function runs until the handler returns a response, exits, or times out.
This page describes how to work with Lambda function handlers in Go, including project setup, naming conventions, and best practices. This page also includes an example of a Go Lambda function that takes in information about an order, produces a text file receipt, and puts this file in an Amazon Simple Storage Service (Amazon S3) bucket. For information about how to deploy your function after writing it, see Deploy Go Lambda functions with .zip file archives or Deploy Go Lambda functions with container images.
Topics
Setting up your Go handler project
A Lambda function written in Gogo mod init
command:
go mod initexample-go
Here, example-go is the module name. You can replace this with
anything. This command initializes your project and generates the
go.mod file that lists your project's dependencies.
Use the go get command to add any external dependencies to your
project. For example, for all Lambda functions in Go, you must include the
github.com/aws/aws-lambda-go/lambdago get command:
go get github.com/aws/aws-lambda-go
Your function code should live in a Go file. In the following example, we name this
file main.go. In this file, you implement your core function logic in
a handler method, as well as a main() function that calls this handler.
Example Go Lambda function code
The following example Go Lambda function code takes in information about an order, produces a text file receipt, and puts this file in an Amazon S3 bucket.
Example main.go Lambda function
package main import ( "context" "encoding/json" "fmt" "log" "os" "strings" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) type Order struct { OrderID string `json:"order_id"` Amount float64 `json:"amount"` Item string `json:"item"` } var ( s3Client *s3.Client ) func init() { // Initialize the S3 client outside of the handler, during the init phase cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { log.Fatalf("unable to load SDK config, %v", err) } s3Client = s3.NewFromConfig(cfg) } func uploadReceiptToS3(ctx context.Context, bucketName, key, receiptContent string) error { _, err := s3Client.PutObject(ctx, &s3.PutObjectInput{ Bucket: &bucketName, Key: &key, Body: strings.NewReader(receiptContent), }) if err != nil { log.Printf("Failed to upload receipt to S3: %v", err) return err } return nil } func handleRequest(ctx context.Context, event json.RawMessage) error { // Parse the input event var order Order if err := json.Unmarshal(event, &order); err != nil { log.Printf("Failed to unmarshal event: %v", err) return err } // Access environment variables bucketName := os.Getenv("RECEIPT_BUCKET") if bucketName == "" { log.Printf("RECEIPT_BUCKET environment variable is not set") return fmt.Errorf("missing required environment variable RECEIPT_BUCKET") } // Create the receipt content and key destination receiptContent := fmt.Sprintf("OrderID: %s\nAmount: $%.2f\nItem: %s", order.OrderID, order.Amount, order.Item) key := "receipts/" + order.OrderID + ".txt" // Upload the receipt to S3 using the helper method if err := uploadReceiptToS3(ctx, bucketName, key, receiptContent); err != nil { return err } log.Printf("Successfully processed order %s and stored receipt in S3 bucket %s", order.OrderID, bucketName) return nil } func main() { lambda.Start(handleRequest) }
This main.go file contains the following sections of code:
-
package main: In Go, the package containing yourfunc main()function must always be namedmain. -
importblock: Use this block to include libraries that your Lambda function requires. -
type Order struct {}block: Define the shape of the expected input event in this Go struct. -
var ()block: Use this block to define any global variables that you'll use in your Lambda function. -
func init() {}: Include any code you want Lambda to run during the during the initialization phase in thisinit()method. -
func uploadReceiptToS3(...) {}: This is a helper method that's referenced by the mainhandleRequesthandler method. -
func handleRequest(ctx context.Context, event json.RawMessage) error {}: This is the main handler method, which contains your main application logic. -
func main() {}: This is a required entry point for your Lambda handler. The argument to thelambda.Start()method is your main handler method.
For this function to work properly, its execution role
must allow the s3:PutObject action. Also, ensure that you define the
RECEIPT_BUCKET environment variable. After a successful invocation, the Amazon S3 bucket
should contain a receipt file.
Handler naming conventions
For Lambda functions in Go, you can use any name for the handler. In this example, the handler
method name is handleRequest. To reference the handler value in your
code, you can use the _HANDLER environment variable.
For Go functions deployed using a