Demo Project for Go using AWS Lambda
https://www.softkraft.co/aws-lambda-in-golang/
- Create Lambda function:
- In Console, search for Lambda.
- In Lambda page, choose Create function.
- In next page:
- Function name: helloLambda, for example.
- Runtime: your language, for example: Go.
- Execution role: Create a new role from aws policy templates
- Role Name: helloLambda-executor - and choose Simple microservice permission
- Creat API:
- In Console search for API Gateway
- In section of REST Api, click Build button.
- In the next page, choose:
- Protocol: REST
- Create new API: New API
- API name: helloLambdaAPI
- After click Create API button, on the next screen:
- Click select box Action and select Create API option.
- Select:
- Integration type: Lambda Function
- Use Lambda Proxy integration: check
- Lambda Function: helloLambda
- Use Default Timeout: check
Demo project: https://github.com/ducminhgd/go-lambda
Simple steps:
- Make sure that you install the dependencies
go get -v all
. - Build project
GOOS=linux go build -o build/main cmd/main.go
. - Zip binary to upload to AWS
zip -jrm build/main.zip build/main
- If you want to handle request and response in your code, then please make sure that the field Use Lambda Proxy integration in Integration Request checked.
Sample code
package main
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
func HandleRequest(ctx context.Context, req events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
name, found := req.QueryStringParameters["name"]
if !found {
name = "Anonymous"
}
resp := events.APIGatewayProxyResponse{Headers: map[string]string{"Content-Type": "text/plain"}}
resp.StatusCode = 200
resp.Body = string(fmt.Sprintf("Hello, %s! Welcome to AWS Lambda", name))
return &resp, nil
}
func main() {
lambda.Start(HandleRequest)
}