Go programming language (also known as “Golang”) is a high-performance programming language based on C that originated at Google. Go was designed to natively handle concurrency and take advantage of multiple cores, so it scales horizontally really well. This feature makes it a great fit for AWS Lambda functions. And how could you not love this little gopher?
Installing Go
I installed Go using apt
:
sudo apt-get update
sudo apt install golang-go
If you're not sure if you have it installed, simply run go version
.
Creating a Lambda in Go
To get started writing Go lambda functions, you will first need to install the lambda Go package, github.com/aws/aws-lambda-go/tree/lambda. The Go installer is go get
, so to install the lambda package, run:
go get github.com/aws/aws-lambda-go/lambda
In order for your Go function to run as a lambda, your main package must have a handler as well as a main()
function. The handler accepts context and event parameters, and the main()
function invokes the handler. The function below is a "hello world" function, so I'm not passing in any event parameters, just a context. To create this lambda, create a directory named src
and add a hello.go
file with the following code:
package main
import (
"context"
"fmt"
"os"
"github.com/aws/aws-lambda-go/lambda"
)
func HandleRequest(ctx context.Context) (string, error) {
var msg = "Hello, world! %s, let's be friends"
var prm = os.Getenv("USER")
return fmt.Sprintf(msg, prm), nil
}
func main() {
lambda.Start(HandleRequest)
}
Deploying the Lambda
I created the Lambda function using the AWS console because it will automatically create the required role. When you create the function, select "Author from scratch", and choose "Go" as the runtime.
To deploy my code, I'll use the AWS CLI. First, we compile the code, then zip it. Then I update the lambda function code from the zip file. I'll also add an environment variable named "USER" since it's referenced in my little sample function.
go build src/hello.go
zip hello.zip hello
aws lambda update-function-code --function-name "go-hello" --zip-file fileb://hello.zip
aws lambda update-function-configuration --function-name "go-hello" --environment Variables={USER=Rachel}
Now that the code is deployed, we'll test it out:
aws lambda invoke --function-name "go-hello" response.json
cat response.json