Skip to content

Commit b306408

Browse files
committed
Golang sample app
1 parent 0d45f4a commit b306408

File tree

11 files changed

+203
-1
lines changed

11 files changed

+203
-1
lines changed

sample-apps/.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,5 @@ build
1010
.gradle
1111
*.zip
1212
bin
13-
obj
13+
obj
14+
main
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#!/bin/bash
2+
BUCKET_ID=$(dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \t\n')
3+
BUCKET_NAME=lambda-artifacts-$BUCKET_ID
4+
echo $BUCKET_NAME > bucket-name.txt
5+
aws s3 mb s3://$BUCKET_NAME

sample-apps/blank-go/2-deploy.sh

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#!/bin/bash
2+
set -eo pipefail
3+
ARTIFACT_BUCKET=$(cat bucket-name.txt)
4+
go get github.com/aws/aws-lambda-go/lambda
5+
go get github.com/aws/aws-lambda-go/lambdacontext
6+
go get github.com/aws/aws-sdk-go/aws
7+
go get github.com/aws/aws-sdk-go/aws/session
8+
go get github.com/aws/aws-sdk-go/service/lambda
9+
cd function
10+
GOOS=linux go build main.go
11+
cd ../
12+
aws cloudformation package --template-file template.yml --s3-bucket $ARTIFACT_BUCKET --output-template-file out.yml
13+
aws cloudformation deploy --template-file out.yml --stack-name blank-go --capabilities CAPABILITY_NAMED_IAM

sample-apps/blank-go/3-invoke.sh

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#!/bin/bash
2+
set -eo pipefail
3+
FUNCTION=$(aws cloudformation describe-stack-resource --stack-name blank-go --logical-resource-id function --query 'StackResourceDetail.PhysicalResourceId' --output text)
4+
5+
while true; do
6+
aws lambda invoke --function-name $FUNCTION --payload file://event.json out.json
7+
cat out.json
8+
echo ""
9+
sleep 2
10+
done

sample-apps/blank-go/4-cleanup.sh

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#!/bin/bash
2+
set -eo pipefail
3+
aws cloudformation delete-stack --stack-name blank-go
4+
echo "Deleted function stack"
5+
if [ -f bucket-name.txt ]; then
6+
ARTIFACT_BUCKET=$(cat bucket-name.txt)
7+
while true; do
8+
read -p "Delete deployment artifacts and bucket ($ARTIFACT_BUCKET)?" response
9+
case $response in
10+
[Yy]* ) aws s3 rb --force s3://$ARTIFACT_BUCKET; rm bucket-name.txt; break;;
11+
[Nn]* ) break;;
12+
* ) echo "Response must start with y or n.";;
13+
esac
14+
done
15+
fi
16+
rm -f out.yml out.json function/main

sample-apps/blank-go/README.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Blank function (Go)
2+
3+
![Architecture](/sample-apps/blank/images/sample-blank.png)
4+
5+
The project source includes function code and supporting resources:
6+
7+
- `function` - A Golang function.
8+
- `template.yml` - An AWS CloudFormation template that creates an application.
9+
- `1-create-bucket.sh`, `2-deploy.sh`, etc. - Shell scripts that use the AWS CLI to deploy and manage the application.
10+
11+
Use the following instructions to deploy the sample application.
12+
13+
# Requirements
14+
- [Go executable](https://golang.org/dl/).
15+
- The Bash shell. For Linux and macOS, this is included by default. In Windows 10, you can install the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to get a Windows-integrated version of Ubuntu and Bash.
16+
- [The AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html).
17+
18+
# Setup
19+
Download or clone this repository.
20+
21+
$ git clone [email protected]:awsdocs/aws-lambda-developer-guide.git
22+
$ cd aws-lambda-developer-guide/sample-apps/blank-go
23+
24+
To create a new bucket for deployment artifacts, run `1-create-bucket.sh`. Or, if you already have a bucket, create a file named `bucket-name.txt` that contains the name of your bucket.
25+
26+
blank-go$ ./1-create-bucket.sh
27+
make_bucket: lambda-artifacts-a5e491dbb5b22e0d
28+
29+
# Deploy
30+
31+
To deploy the application, run `2-deploy.sh`.
32+
33+
blank-go$ ./2-deploy.sh
34+
Successfully packaged artifacts and wrote output template to file out.yml.
35+
Waiting for changeset to be created..
36+
Successfully created/updated stack - blank-go
37+
38+
This script uses AWS CloudFormation to deploy the Lambda functions and an IAM role. If the AWS CloudFormation stack that contains the resources already exists, the script updates it with any changes to the template or function code.
39+
40+
# Test
41+
To invoke the function, run `3-invoke.sh`.
42+
43+
blank-go$ ./3-invoke.sh
44+
{
45+
"StatusCode": 200,
46+
"ExecutedVersion": "$LATEST"
47+
}
48+
"{\"FunctionCount\":42,\"TotalCodeSize\":361861771}"
49+
50+
The application uses AWS X-Ray to trace requests. Open the [X-Ray console](https://console.aws.amazon.com/xray/home#/service-map) to view the service map.
51+
52+
![Service Map](/sample-apps/blank-go/images/blank-go-servicemap.png)
53+
54+
Choose a node in the main function graph. Then choose **View traces** to see a list of traces. Choose any trace to view a timeline that breaks down the work done by the function.
55+
56+
![Trace](/sample-apps/blank-go/images/blank-go-trace.png)
57+
58+
# Cleanup
59+
To delete the application, run `4-cleanup.sh`.
60+
61+
blank$ ./4-cleanup.sh

sample-apps/blank-go/event.json

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"Records": [
3+
{
4+
"messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78",
5+
"receiptHandle": "MessageReceiptHandle",
6+
"body": "Hello from SQS!",
7+
"attributes": {
8+
"ApproximateReceiveCount": "1",
9+
"SentTimestamp": "1523232000000",
10+
"SenderId": "123456789012",
11+
"ApproximateFirstReceiveTimestamp": "1523232000001"
12+
},
13+
"messageAttributes": {},
14+
"md5OfBody": "7b270e59b47ff90a553787216d55d91d",
15+
"eventSource": "aws:sqs",
16+
"eventSourceARN": "arn:aws:sqs:us-west-2:123456789012:MyQueue",
17+
"awsRegion": "us-west-2"
18+
}
19+
]
20+
}

sample-apps/blank-go/function/main.go

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package main
2+
3+
import (
4+
"os"
5+
"fmt"
6+
"log"
7+
"context"
8+
"encoding/json"
9+
runtime "github.com/aws/aws-lambda-go/lambda"
10+
"github.com/aws/aws-lambda-go/events"
11+
"github.com/aws/aws-lambda-go/lambdacontext"
12+
"github.com/aws/aws-sdk-go/aws/session"
13+
"github.com/aws/aws-sdk-go/service/lambda"
14+
)
15+
16+
var client = lambda.New(session.New())
17+
18+
func init() {
19+
callLambda()
20+
}
21+
22+
func callLambda() (string, error) {
23+
input := &lambda.GetAccountSettingsInput{}
24+
req, resp := client.GetAccountSettingsRequest(input)
25+
err := req.Send()
26+
output, _ := json.Marshal(resp.AccountUsage)
27+
return string(output), err
28+
}
29+
30+
func handleRequest(ctx context.Context, event events.SQSEvent) (string, error) {
31+
// event
32+
eventJson, _ := json.MarshalIndent(event, "", " ")
33+
log.Printf("EVENT: %s", eventJson)
34+
// environment variables
35+
log.Printf("REGION: %s", os.Getenv("AWS_REGION"))
36+
log.Println("ALL ENV VARS:")
37+
for _, element := range os.Environ() {
38+
log.Println(element)
39+
}
40+
// request context
41+
lc, _ := lambdacontext.FromContext(ctx)
42+
log.Printf("REQUEST ID: %s", lc.AwsRequestID)
43+
// global variable
44+
log.Printf("FUNCTION NAME: %s", lambdacontext.FunctionName)
45+
// context method
46+
deadline, _ := ctx.Deadline()
47+
log.Printf("DEADLINE: %s", deadline)
48+
// AWS SDK call
49+
usage, err := callLambda()
50+
if err != nil {
51+
return "ERROR", err
52+
}
53+
return fmt.Sprint(usage), nil
54+
}
55+
56+
func main() {
57+
runtime.Start(handleRequest)
58+
}
Loading
63.1 KB
Loading

sample-apps/blank-go/template.yml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
AWSTemplateFormatVersion: '2010-09-09'
2+
Transform: 'AWS::Serverless-2016-10-31'
3+
Description: An AWS Lambda application that calls the Lambda API.
4+
Resources:
5+
function:
6+
Type: AWS::Serverless::Function
7+
Properties:
8+
Handler: main
9+
Runtime: go1.x
10+
CodeUri: function/.
11+
Description: Call the AWS Lambda API
12+
Timeout: 5
13+
# Function's execution role
14+
Policies:
15+
- AWSLambdaBasicExecutionRole
16+
- AWSLambdaReadOnlyAccess
17+
- AWSXrayWriteOnlyAccess
18+
Tracing: Active

0 commit comments

Comments
 (0)