AWS Lambda with Golang

Go is a programming language designed by Google. It is a statically typed, compiled language with
the added benefit of memory safety, garbage collection, structural typing and compiles to a static binary. When compared
to interpreted languages like Python, the biggest benefit is the small binary size and fast execution. AWS Lambda supports
the Go programming language as a function handler. Lets take a look!

A Lambda Handler in Go

A lambda that handles an APIGatewayProxyRequest and responds with an APIGatewayProxyResponse looks like below:

package main

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

func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {

    // stdout and stderr are sent to AWS CloudWatch Logs
   log.Printf("Processing Lambda request %s\n", request.RequestContext.RequestID)

    return events.APIGatewayProxyResponse{
        Body:       "Hello World!",
        StatusCode: 200,
    }, nil
}

func main() {
    lambda.Start(Handler)
}

The lambda is fully typed, returns an APIGatewayProxyResponse and compiles to a Linux static binary of 8 megabytes.

Packaging the Lambda

The lambda can be created by typing go build src/github.com/dnvriend/lambda/main.go. The resulting lambda is called
main and can be zipped by typing: zip dist/lambda.zip main. The resulting archive can be uploaded to S3 and used
for deploying a lambda.

Example

The example repository shows how to create and build a lambda.
The lambda calls responds with Hello World! and can be invoked from your browser.

Using the example

I assume you have a mac with Go and sceptre installed. To run the example type make deploy.
To get the url of the api gateway, type make info. To remove the example type make delete.

Conclusion

AWS Lambda supports the Go programming language. AWS also provides an AWS SDK for Go.
Using both AWS Lambda and the AWS SDK, you can create fast and highly scalable, serverless functions that can integrate
with AWS services. Iit is easy to create an API Gateway handler or a Kinesis stream processor.

Share this article: Tweet this post / Post on LinkedIn