Article

AWS Lambda is a powerful serverless computing service that enables developers to run code without provisioning or managing servers. This guide provides a comprehensive step-by-step approach to creating and deploying an AWS Lambda function using Go (Golang).

Prerequisites

Before proceeding, ensure the following are installed and configured:

  • AWS CLI
  • AWS account with appropriate permissions
  • Go (Golang) installed on the local machine
  • Serverless framework (optional but recommended)

Step 1: Install AWS CLI and Configure Credentials

To interact with AWS services, install and configure AWS CLI:

aws configure

Enter the AWS Access Key, Secret Access Key, default region, and output format when prompted.

Step 2: Install Go and Set Up the Development Environment

Download and install Go from the official website golang.org. Verify the installation:

go version

Set up a new Go project directory:

mkdir aws-lambda-go && cd aws-lambda-go

Step 3: Write the Go Code for AWS Lambda Function

Create a new Go file (e.g., main.go) and implement the Lambda function:

package main

import (

“context”

“fmt”

“github.com/aws/aws-lambda-go/lambda”

)

type Request struct {

Name string `json:”name”`

}

type Response struct {

Message string `json:”message”`

}

func handler(ctx context.Context, req Request) (Response, error) {

return Response{Message: fmt.Sprintf(“Hello, %s!”, req.Name)}, nil

}

func main() {

lambda.Start(handler)

}

Step 4: Build and Package the Go Lambda Function

Compile the Go binary for AWS Lambda’s execution environment:

GOOS=linux GOARCH=amd64 go build -o main main.go

Compress the binary:

zip function.zip main

Step 5: Create and Deploy the AWS Lambda Function

Upload the function to AWS Lambda:

aws lambda create-function –function-name goLambdaFunction \

–runtime go1.x –role arn:aws:iam::YOUR_AWS_ACCOUNT_ID:role/YOUR_LAMBDA_ROLE \

–handler main –zip-file fileb://function.zip

Replace YOUR_AWS_ACCOUNT_ID and YOUR_LAMBDA_ROLE with actual values.

Step 6: Test the AWS Lambda Function

Invoke the function using AWS CLI:

aws lambda invoke –function-name goLambdaFunction output.txt

 

To test with input parameters:

aws lambda invoke –function-name goLambdaFunction –payload ‘{“name”: “John”}’ response.json

Step 7: Update the AWS Lambda Function

Modify the code and repackage the function. Then, update Lambda:

aws lambda update-function-code –function-name goLambdaFunction –zip-file fileb://function.zip

Step 8: Configure API Gateway for HTTP Access (Optional)

To expose the function via HTTP, configure an AWS API Gateway and link it to the Lambda function. This can be done via AWS Console or the AWS CLI.

Conclusion

AWS Lambda and Go provide a scalable and efficient way to run serverless applications. By following this guide, developers can successfully create, deploy, and manage Lambda functions with Go.