Writing Go-based function handler for AWS Lambda
Deploying Go-Based application on AWS Lambda.
Introduction
Function handlers are a piece of code in an application that is invoked when an event is called. These events are triggers in AWS Lambda which is very well integrated with other AWS services. A trigger can be an API Gateway, an object creation in S3, or an SQS.
Tip: If you are new to GoLang, Please visit the below link for a better understanding of Go.
A video guide is also attached to the blog
The requirement for writing the Go program
For executing any GO program, the following steps must be followed.
- An installation of Go. For installation instructions, see Installing Go.
- An IDE to edit your code. (I’ll be using VSCode)
- A command terminal.
Writing the Lambda function handler code
(you can find the code and build file on my Github)
- Create a folder for our project
mkdir go-lambda
cd go-lambda
- Create a module file for dependencies. Run the go mod init command, giving it the path of the module your code will be in.
go mod init example/go-lambda
This command creates a go.mod file in which dependencies you add will be listed for tracking.
- In the file main.go, write the code that will be executed when the lambda function is called.
Building the Go project for Lambda
- Run the build command to create an executable file. the below command is for macOS but you can visit this link to create the same for windows.
GOOS=linux GOARCH=amd64 go build -o main main.go
A build file with the name main will be created.
- Zip the build file as lambda accepts the .zip file.
zip main.zip main
once the zip is available we will add it to lambda.
Creation of Lambda function
- Login to AWS Console, navigate to the Lambda function, and click on create Lambda.
- add a name to your function and select Go as runtime and click on create function.
Add the handler as main.
- Now we will add the go build that we created earlier. Click on upload from in the code source section.
- now that our build is uploaded we will test the application.
Navigate to the test tab in the Lambda console and add the below request and hit test.
{
"name": "Ram"
}
We got our response… and you successfully created a GoLang-based lambda.
Conclusion
In this article, we have discussed how to write Go based event listener for AWS lambda and implemented it step by step, Right from writing the Go code to building it and finally adding it to AWS Lambda.
Thanks for reading. I hope this story was helpful.
If you are interested, check out my other articles.
you can also visit shubhamdeshmukh.com