/short-url-aws-lambda

simple short url application by aws sam and lambda

Primary LanguageGo

short-url-aws-lambda

This is a sample template for short-url-aws-lambda - Below is a brief explanation of what we have generated for you:

.
├── Makefile                    <-- Make to automate build
├── README.md                   <-- This instructions file
├── shorten                     <-- Source code for a lambda function
│   ├── main.go                 <-- Lambda function code
│   └── main_test.go            <-- Unit tests
│   └── Dockerfile              <-- Dockerfile
├── redirect                    <-- Source code for a lambda function
│   ├── main.go                 <-- Lambda function code
│   └── main_test.go            <-- Unit tests
│   └── Dockerfile              <-- Dockerfile
└── template.yaml

Requirements

You may need the following for local testing.

Building and deployment

Create two new ECR repositories

aws ecr create-repository --repository-name lambda-shorten \
--image-tag-mutability IMMUTABLE --image-scanning-configuration scanOnPush=true
aws ecr create-repository --repository-name lambda-redirect \
--image-tag-mutability IMMUTABLE --image-scanning-configuration scanOnPush=true

Create a new S3 bucket

aws s3 mb s3://${your_bucket_name}

SAM Build

sam build

SAM Deploy

  1. Use AWS CLI with Parameters
sam deploy \
--stack-name ${your_stack_name} \
--s3-bucket ${your_bucket_name} \
--s3-prefix ${prefix_text} \
--region ${lambda_region} \
--confirm-changeset \
capabilities CAPABILITY_IAM \
--parameter-overrides TableName=${dynamodb_table_name} \
--image-repositories ShortenFunction=${your_aws_account_id}.dkr.ecr.${lambda_region}.amazonaws.com/lambda-shorten \
--image-repositories RedirectFunction=${your_aws_account_id}.dkr.ecr.${lambda_region}.amazonaws.com/lambda-redirect
  1. Use AWS CLI with samconfig.toml

samconfig.toml

version = 0.1
[default]
[default.deploy]
[default.deploy.parameters]
stack_name = "${your_stack_name}"
s3_bucket = "${your_bucket_name}"
s3_prefix = "${prefix_text}"
region = "${lambda_region}"
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
parameter_overrides = "TableName=${dynamodb_table_name}"
image_repositories = [
	"ShortenFunction=${your_aws_account_id}.dkr.ecr.${lambda_region}.amazonaws.com/sample-shorten",
	"RedirectFunction=${your_aws_account_id}.dkr.ecr.${lambda_region}.amazonaws.com/sample-redirect"
]

sam deploy

sam deploy

Testing

  1. Test ShortenFunction

Request

curl -X POST -H 'Content-Type: application/json' -d '{"url": "${test_url}"}' \
https://${random_string}.execute-api.${lambda_region}.amazonaws.com/Prod/shorten

Response

{"short_url": "HAlqGWK7R"}
  1. Test RedirectFunction

Open the browser and enter the Short URL

https://${random_string}.execute-api.${lambda_region}.amazonaws.com/Prod/HAlqGWK7R

Destory Resources

sam delete --stack-name ${your_stack_name}