Skip to main content

AWS Lambda – Function in Go

 Go Language support is a recent addition to AWS. To work with Go, you need to select the language from AWS console while creating the AWS Lambda function. In this chapter, let us learn in detail about AWS Lambda function in Go language.

Installing Go

To get started we need Go Language support. In this section, we will go through following details to start working with AWS Lambda in Go. This is the official site for Go download: https://golang.org/dl/

Go Programming

Now, download the package as per the operating system. Follow the procedure given here to install Go on the respective operating system.

Installation on Windows

Observe that for Windows, there is 32-bit and 64-bit download available. Download the zip file and extract the contents and store it in a directory of your choice.

Add the environment variables available at ControlPanel ---> System ---> Advanced system settings.

System Properties

Now, click Environment Variables button and add the directory path as shown here −

Environment Variables Go

You can also edit the system variable as shown here −

Edit System Variable

Once these steps are done, you should be able to start working with Go. Open command prompt and check the Go command for version. Observe the following screenshot for the same.

Command Prompt
Installation for Linux and Mac OS

For installing packages on Linux and Mac OS, follow the instruction as shown below −

Unpack the packages and store it at the location /usr/local/go. Now, add /usr/local/go/bin to the PATH environment variable. It can be done using /etc/profile or $HOME/.profile.

For this purpose, you can use the following command

export PATH=$PATH:/usr/local/go/bin

To add AWS support to for Windows, Linux and mac, use the following in your git command line −

go.exe get -u github.com/aws/aws-lambda-go/lambda 
go.exe get -u github.com/aws/aws-lambda-go/lambdacontext
go.exe get -u github.com/aws/aws-lambda-go/cmd/build-lambda-zip

To compile the code Windows/Linux/Mac, use the following commands −

GOOS=linux GOARCH=amd64 go build -o main main.go
%GOPATH%\bin\build-lambda-zip.exe -o main.zip main


AWS Lambda Function using GO

A program returned in Go when build gives an executable file. The following is a simple program in Go with AWS Lambda support. We need to import the github.com/aws/aws-lambda-go/lambda, as this has the Lambda programming functionality.Another important need for AWS Lambda is the handler.

Main.go
// main.go
package main

import (
"github.com/aws/aws-lambda-go/lambda"
)
func hello() (string, error) {
return "Hello Lambda", nil
}
func main() {
// Make the handler available for Remote Procedure Call by AWS Lambda
lambda.Start(hello)
}

Note that the execution of the Go program starts from main where lambda. start is called with the handler function. Observe the code shown below −

func main() {
// Make the handler available for Remote Procedure Call by AWS Lambda
lambda.Start(hello)
}

Now, let us execute the above file using Go command and then zip the executable file.

The structure of the file we have been using is as shown here −

Structure File

Structure File Output

With go build, it creates an executable file called main.exe. To zip the file and upload it in AWS Lambda, you can use the following procedure −

To compile the code Windows/Linux/Mac, use the following commands −

GOOS=linux GOARCH=amd64 go build -o main main.go
%GOPATH%\bin\build-lambda-zip.exe -o main.zip main

Then, login into AWS console and create Lambda function using Go as runtime −

APIws Console Go

Once the function is created, upload the executable zip file created above.

Lambda function handler with Go

Handler is where the execution of the Go program starts. From main call to lambda.start, execution is called with the handler function. Note that the handler to be added will be main.

Observe the code here for an understanding −

func main() {
// Make the handler available for Remote Procedure Call by AWS Lambda
lambda.Start(hello)
}

Follow as per the screenshots given below −

Function Code

Execution Role Go

Now, save the function and test it. You can see the execution result as shown here.

Execution Result Go

The corresponding log output will be as shown here −

Log Output Go
Context object with Go

AWS Lambda in Go gives following global variables and properties for context.

  • MemoryLimitInMB − Memory limit, in MB that is configured in aws lambda.
  • FunctionName − name of aws lambda function.
  • FunctionVersion − the version of aws lambda function executing.
  • LogStreamName − cloudwatch log stream name.
  • LogGroupName − cloudwatch group name.

The properties available on context are given as under −

AwsRequestID

This is AWS request id which you get when AWS Lambda function is invoked.

ClientContext

This contains details about the client application and device when invoked through the AWS Mobile SDK. It can be null. Client context provides details like client ID, application title, version name, version code, and the application package name.

InvokedFunctionArn

The ARN of the function invoked. An unqualified ARN executes the $LATEST version and aliases execute the function version it is pointing to.

Identity

It gives details about the Amazon Cognito identity provider when used with AWS mobile SDK.

The changes added to main.go to print context details −

// main.go
package main

import (
"context"
"log"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/lambdacontext"
)

func hello
(ctx context.Context) (string, error) {
lc
, _ := lambdacontext.FromContext(ctx);
log
.Print(lc);
log
.Print(lc.AwsRequestID);
log
.Print(lc.InvokedFunctionArn);
return "Hello Lambda", nil
}

func main
() {
// Make the handler available for Remote Procedure Call by AWS Lambda
lambda.Start(hello)
}

We need to import the log and lambda context to use it with Go. The context details are as follows −

func hello(ctx context.Context) (string, error) {
lc, _ := lambdacontext.FromContext(ctx);
log.Print(lc);
log.Print(lc.AwsRequestID);
log.Print(lc.InvokedFunctionArn);
return "Hello Lambda", nil
}

You can observe the following output on testing the above code −

Execution Result Output
Logging data

With Go you can log data using the log or fmt module as shown below −

// main.go
package main

import (
"log"
"fmt"
"github.com/aws/aws-lambda-go/lambda"
)

func hello() (string, error) {
log.Print("Hello from Lambda Go using log");
fmt.Print("Hello from Lambda Go using fmt");
return "Hello Lambda", nil
}

func main() {
// Make the handler available for Remote Procedure Call by AWS Lambda
lambda.Start(hello)
}

The output for same is as shown below −

Logging Data

Checking Logs in CloudWatch

You can see the logs in CloudWatch also. For this, go to AWS service and select cloudwatch and click Logs on left side. Now, search for Lambda function in the list to see the logs −

Checking Logs

Function Errors

You can create custom error handling in AWS Lambda using the errors module as shown in the code below −

// main.go
package main
import (
"errors"
"github.com/aws/aws-lambda-go/lambda"
)

func hello() error {
return errors.New("There is an error in the code!")
}

func main() {
// Make the handler available for Remote Procedure Call by AWS Lambda
lambda.Start(hello)
}

The output for the code shown above is as given below −

Function Errors

Comments

Popular posts from this blog

C++ How to use Date and Time

The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program. There are four time-related types: clock_t, time_t, size_t , and tm . The types clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer. The structure type tm holds the date and time in the form of a C structure having the following elements: struct tm { int tm_sec ; // seconds of minutes from 0 to 61 int tm_min ; // minutes of hour from 0 to 59 int tm_hour ; // hours of day from 0 to 24 int tm_mday ; // day of month from 1 to 31 int tm_mon ; // month of year from 0 to 11 int tm_year ; // year since 1900 int tm_wday ; // days since sunday int tm_yday ; // days since January 1st int tm_isdst ; // hours of daylight savin...

Lambda Function with Amazon DynamoDB

DynamoDB can trigger AWS Lambda when the data in added to the tables, updated or deleted. In this chapter, we will work on a simple example that will add items to the DynamoDB table and AWS Lambda which will read the data and send mail with the data added. Requisites To use Amazon DB and AWS Lambda, we need to follow the steps as shown below − Create a table in DynamoDB with primary key Create a role which will have permission to work with DynamoDBand AWS Lambda. Create function in AWS Lambda AWS Lambda Trigger to send mail Add data in DynamoDB Let us discuss each of this step in detail. Example We are going to work out on following example which shows the basic interaction between DynamoDB and AWS Lambda. This example will help you to understand the following operations − Creating a table called customer in Dynamodb table and how to enter data in that table. Triggering AWS Lambda function once the data is entered and sending mail using Amazon SES service. The basic block diagram that ...

PERL Some good framework

1. Catalyst is the most popular agile Perl MVC web framework that encourages rapid development and clean design without getting in your way. Catalyst | Perl MVC web application framework 2. Mojolicious is a next generation web framework for the Perl programming language. Back in the early days of the web, many people learned Perl because of a wonderful Perl   ... Mojolicious - Perl real-time web framework 3. Documents for Perl  The Perl Archive Network, the gateway to all things Perl. The canonical location for Perl code and modules. The Comprehensive Perl Archive Network - www. cpan .org