diff --git a/al2023/go/hello-img/README.md b/al2023/go/hello-img/README.md new file mode 100644 index 000000000..d6af33a92 --- /dev/null +++ b/al2023/go/hello-img/README.md @@ -0,0 +1,49 @@ +# Cookiecutter SAM for golang Lambda functions + +This is a [Cookiecutter](https://github.com/audreyr/cookiecutter) template to create a Serverless App based on Serverless Application Model (SAM). + +It is important to note that you should not try to `git clone` this project but use `cookiecutter` CLI instead as ``\\{\\{cookiecutter.project_slug\\}\\}`` will be rendered based on your input and therefore all variables and files will be rendered properly. + +## Requirements + +Install `cookiecutter` command line: + +**Pip users**: + +* `pip install cookiecutter` + +**Homebrew users**: + +* `brew install cookiecutter` + +**Windows or Pipenv users**: + +* `pipenv install cookiecutter` + +**NOTE**: [`Pipenv`](https://github.com/pypa/pipenv) is the new and recommended Python packaging tool that works across multiple platforms and makes Windows a first-class citizen. + +## Usage + +Generate a new SAM based Serverless App: `cookiecutter gh:aws-samples/cookiecutter-aws-sam-golang`. + +You'll be prompted a few questions to help this cookiecutter template to scaffold this project and after its completed you should see a new folder at your current path with the name of the project you gave as input. + +**NOTE**: After you understand how cookiecutter works (cookiecutter.json, mainly), you can fork this repo and apply your own mechanisms to accelerate your development process and this can be followed for any programming language and OS. + +## Options + +Option | Description +------------------------------------------------- | --------------------------------------------------------------------------------- +`include_apigw` | Includes sample code for API Gateway Proxy integration for Lambda and a Catch All method in SAM as a starting point +`include_xray` | Includes both sample code for getting started with AWS X-Ray and adds necessary permission and `Tracing` to your function +`include_safe_deployment` | Sends by default 10% of traffic for every 1 minute to a newly deployed function using [CodeDeploy + SAM integration](https://github.com/awslabs/serverless-application-model/blob/master/docs/safe_lambda_deployments.rst) - Linear10PercentEvery1Minute +`include_experimental_make` | Includes a `Makefile` for advanced users to automate packaging, build, tests and SAM Local - Only works on OSX/Linux at the moment + +## Credits + +* This project has been generated with [Cookiecutter](https://github.com/audreyr/cookiecutter) +* [Bruno Alla's Lambda function template](https://github.com/browniebroke/cookiecutter-lambda-function) + +## License + +This project is licensed under the terms of the [MIT License with no attribution](/LICENSE) \ No newline at end of file diff --git a/al2023/go/hello-img/__init__.py b/al2023/go/hello-img/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/al2023/go/hello-img/cookiecutter.json b/al2023/go/hello-img/cookiecutter.json new file mode 100644 index 000000000..883cf95ad --- /dev/null +++ b/al2023/go/hello-img/cookiecutter.json @@ -0,0 +1,10 @@ +{ + "project_name": "Name of the project", + "runtime": "go", + "architectures": { + "value": [ "x86_64", "arm64" ] + }, + "_copy_without_render": [ + ".gitignore" + ] +} diff --git a/al2023/go/hello-img/requirements-dev.txt b/al2023/go/hello-img/requirements-dev.txt new file mode 100644 index 000000000..aa7117612 --- /dev/null +++ b/al2023/go/hello-img/requirements-dev.txt @@ -0,0 +1,4 @@ +cookiecutter==2.1.1 +flake8==3.5.0 +pytest==3.3.2 +pytest-cookies==0.3.0 diff --git a/al2023/go/hello-img/tests/__init__.py b/al2023/go/hello-img/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/al2023/go/hello-img/tests/test_bake_project.py b/al2023/go/hello-img/tests/test_bake_project.py new file mode 100644 index 000000000..ab81949ba --- /dev/null +++ b/al2023/go/hello-img/tests/test_bake_project.py @@ -0,0 +1,78 @@ +from contextlib import contextmanager + +import os + + +@contextmanager +def inside_dir(dirpath): + """ + Execute code from inside the given directory + :param dirpath: String, path of the directory the command is being run. + """ + old_path = os.getcwd() + try: + os.chdir(dirpath) + yield + finally: + os.chdir(old_path) + + +def test_project_tree(cookies): + result = cookies.bake(extra_context={"project_name": "test_project"}) + assert result.exit_code == 0 + assert result.exception is None + assert result.project.basename == "test_project" + + assert result.project.isdir() + assert result.project.join("README.md").isfile() + assert result.project.join("template.yaml").isfile() + assert result.project.join("hello-world").isdir() + assert result.project.join("hello-world", "main.go").isfile() + assert result.project.join("hello-world", "main_test.go").isfile() + + +def test_app_content(cookies): + result = cookies.bake(extra_context={"project_name": "test_project"}) + app_file = result.project.join("hello-world", "main.go") + app_content = app_file.readlines() + app_content = "".join(app_content) + + contents = ( + "github.com/aws/aws-lambda-go/events", + "sourceIP := request.RequestContext.Identity.SourceIP", + "lambda.Start(handler)" + ) + + for content in contents: + assert content in app_content + + +def test_app_test_content(cookies): + result = cookies.bake(extra_context={"project_name": "test_project"}) + app_file = result.project.join("hello-world", "main_test.go") + app_content = app_file.readlines() + app_content = "".join(app_content) + + contents = ( + "func TestHandler(t *testing.T)", + "SourceIP: \"127.0.0.1\"", + "response, err := handler(testCase.request)" + ) + + for content in contents: + assert content in app_content + + +def test_app_template_content(cookies): + result = cookies.bake(extra_context={"project_name": "test_project"}) + app_file = result.project.join("template.yaml") + app_content = app_file.readlines() + app_content = "".join(app_content) + + contents = ( + "Runtime: go1.x", + "HelloWorldFunction", + ) + + for content in contents: + assert content in app_content diff --git a/al2023/go/hello-img/{{cookiecutter.project_name}}/README.md b/al2023/go/hello-img/{{cookiecutter.project_name}}/README.md new file mode 100644 index 000000000..3a5eca541 --- /dev/null +++ b/al2023/go/hello-img/{{cookiecutter.project_name}}/README.md @@ -0,0 +1,137 @@ +# {{ cookiecutter.project_name }} + +This is a sample template for {{ cookiecutter.project_name }} - Below is a brief explanation of what we have generated for you: + +```bash +. +├── README.md <-- This instructions file +├── hello-world <-- Source code for a lambda function +│ ├── main.go <-- Lambda function code +│ └── main_test.go <-- Unit tests +│ └── Dockerfile <-- Dockerfile +└── template.yaml +``` + +## Requirements + +* AWS CLI already configured with Administrator permission +* [Docker installed](https://www.docker.com/community-edition) +* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) + +You may need the following for local testing. +* [Golang](https://golang.org) + +## Setup process + +### Installing dependencies & building the target + +In this example we use the built-in `sam build` to build a docker image from a Dockerfile and then copy the source of your application inside the Docker image. +Read more about [SAM Build here](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-build.html) + +### Local development + +**Invoking function locally through local API Gateway** + +```bash +sam local start-api +``` + +If the previous command ran successfully you should now be able to hit the following local endpoint to invoke your function `http://localhost:3000/hello` + +**SAM CLI** is used to emulate both Lambda and API Gateway locally and uses our `template.yaml` to understand how to bootstrap this environment (runtime, where the source code is, etc.) - The following excerpt is what the CLI will read in order to initialize an API and its routes: + +```yaml +... +Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get +``` + +## Packaging and deployment + +AWS Lambda Golang runtime requires a flat folder with the executable generated on build step. SAM will use `CodeUri` property to know where to look up for the application: + +```yaml +... + FirstFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: hello_world/ + ... +``` + +To deploy your application for the first time, run the following in your shell: + +```bash +sam deploy --guided +``` + +The command will package and deploy your application to AWS, with a series of prompts: + +* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. +* **AWS Region**: The AWS region you want to deploy your app to. +* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. +* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. +* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. + +You can find your API Gateway Endpoint URL in the output values displayed after deployment. + +### Testing + +We use `testing` package that is built-in in Golang and you can simply run the following command to run our tests locally: + +```shell +cd ./hello-world/ +go test -v . +``` +# Appendix + +### Golang installation + +Please ensure Go 1.x (where 'x' is the latest version) is installed as per the instructions on the official golang website: https://golang.org/doc/install + +A quickstart way would be to use Homebrew, chocolatey or your linux package manager. + +#### Homebrew (Mac) + +Issue the following command from the terminal: + +```shell +brew install golang +``` + +If it's already installed, run the following command to ensure it's the latest version: + +```shell +brew update +brew upgrade golang +``` + +#### Chocolatey (Windows) + +Issue the following command from the powershell: + +```shell +choco install golang +``` + +If it's already installed, run the following command to ensure it's the latest version: + +```shell +choco upgrade golang +``` + +## Bringing to the next level + +Here are a few ideas that you can use to get more acquainted as to how this overall process works: + +* Create an additional API resource (e.g. /hello/{proxy+}) and return the name requested through this new path +* Update unit test to capture that +* Package & Deploy + +Next, you can use the following resources to know more about beyond hello world samples and how others structure their Serverless applications: + +* [AWS Serverless Application Repository](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/al2023/go/hello-img/{{cookiecutter.project_name}}/events/event.json b/al2023/go/hello-img/{{cookiecutter.project_name}}/events/event.json new file mode 100644 index 000000000..a429ac5e5 --- /dev/null +++ b/al2023/go/hello-img/{{cookiecutter.project_name}}/events/event.json @@ -0,0 +1,63 @@ +{ + "body": "{\"message\": \"hello world\"}", + "resource": "/hello", + "path": "/hello", + "httpMethod": "GET", + "isBase64Encoded": false, + "queryStringParameters": { + "foo": "bar" + }, + "pathParameters": { + "proxy": "/path/to/resource" + }, + "stageVariables": { + "baz": "qux" + }, + "headers": { + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Accept-Encoding": "gzip, deflate, sdch", + "Accept-Language": "en-US,en;q=0.8", + "Cache-Control": "max-age=0", + "CloudFront-Forwarded-Proto": "https", + "CloudFront-Is-Desktop-Viewer": "true", + "CloudFront-Is-Mobile-Viewer": "false", + "CloudFront-Is-SmartTV-Viewer": "false", + "CloudFront-Is-Tablet-Viewer": "false", + "CloudFront-Viewer-Country": "US", + "Host": "1234567890.execute-api.us-east-1.amazonaws.com", + "Upgrade-Insecure-Requests": "1", + "User-Agent": "Custom User Agent String", + "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", + "X-Forwarded-For": "127.0.0.1, 127.0.0.2", + "X-Forwarded-Port": "443", + "X-Forwarded-Proto": "https" + }, + "requestContext": { + "accountId": "123456789012", + "resourceId": "123456", + "stage": "prod", + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "requestTime": "09/Apr/2015:12:34:56 +0000", + "requestTimeEpoch": 1428582896000, + "identity": { + "cognitoIdentityPoolId": null, + "accountId": null, + "cognitoIdentityId": null, + "caller": null, + "accessKey": null, + "sourceIp": "127.0.0.1", + "cognitoAuthenticationType": null, + "cognitoAuthenticationProvider": null, + "userArn": null, + "userAgent": "Custom User Agent String", + "user": null + }, + "path": "/prod/hello", + "resourcePath": "/hello", + "httpMethod": "POST", + "apiId": "1234567890", + "protocol": "HTTP/1.1" + } + } + \ No newline at end of file diff --git a/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/Dockerfile b/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/Dockerfile new file mode 100644 index 000000000..422fd966b --- /dev/null +++ b/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/Dockerfile @@ -0,0 +1,7 @@ +FROM public.ecr.aws/docker/library/golang:1.19 as build-image +WORKDIR /src +COPY go.mod go.sum main.go ./ +RUN go build -o lambda-handler +FROM public.ecr.aws/lambda/provided:al2023 +COPY --from=build-image /src/lambda-handler . +ENTRYPOINT ./lambda-handler diff --git a/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/go.mod b/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/go.mod new file mode 100644 index 000000000..07c218933 --- /dev/null +++ b/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/go.mod @@ -0,0 +1,5 @@ +module hello-world + +go 1.19 + +require github.com/aws/aws-lambda-go v1.36.1 diff --git a/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/go.sum b/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/go.sum new file mode 100644 index 000000000..849813480 --- /dev/null +++ b/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/go.sum @@ -0,0 +1,8 @@ +github.com/aws/aws-lambda-go v1.35.0 h1:iocVDy5Cw5SCRrKOPHwarkdFwwy48OkfmHoE6SJ3ATg= +github.com/aws/aws-lambda-go v1.35.0/go.mod h1:jwFe2KmMsHmffA1X2R09hH6lFzJQxzI8qK17ewzbQMM= +github.com/aws/aws-lambda-go v1.36.1 h1:CJxGkL9uKszIASRDxzcOcLX6juzTLoTKtCIgUGcTjTU= +github.com/aws/aws-lambda-go v1.36.1/go.mod h1:jwFe2KmMsHmffA1X2R09hH6lFzJQxzI8qK17ewzbQMM= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/main.go b/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/main.go new file mode 100644 index 000000000..55d93a3da --- /dev/null +++ b/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/main.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + + "github.com/aws/aws-lambda-go/events" + "github.com/aws/aws-lambda-go/lambda" +) + +func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { + var greeting string + sourceIP := request.RequestContext.Identity.SourceIP + + if sourceIP == "" { + greeting = "Hello, world!\n" + } else { + greeting = fmt.Sprintf("Hello, %s!\n", sourceIP) + } + + return events.APIGatewayProxyResponse{ + Body: greeting, + StatusCode: 200, + }, nil +} + +func main() { + lambda.Start(handler) +} diff --git a/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/main_test.go b/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/main_test.go new file mode 100644 index 000000000..b69105174 --- /dev/null +++ b/al2023/go/hello-img/{{cookiecutter.project_name}}/hello-world/main_test.go @@ -0,0 +1,60 @@ +package main + +import ( + "testing" + + "github.com/aws/aws-lambda-go/events" +) + +func TestHandler(t *testing.T) { + testCases := []struct { + name string + request events.APIGatewayProxyRequest + expectedBody string + expectedError error + }{ + { + // mock a request with an empty SourceIP + name: "empty IP", + request: events.APIGatewayProxyRequest{ + RequestContext: events.APIGatewayProxyRequestContext{ + Identity: events.APIGatewayRequestIdentity{ + SourceIP: "", + }, + }, + }, + expectedBody: "Hello, world!\n", + expectedError: nil, + }, + { + // mock a request with a localhost SourceIP + name: "localhost IP", + request: events.APIGatewayProxyRequest{ + RequestContext: events.APIGatewayProxyRequestContext{ + Identity: events.APIGatewayRequestIdentity{ + SourceIP: "127.0.0.1", + }, + }, + }, + expectedBody: "Hello, 127.0.0.1!\n", + expectedError: nil, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + response, err := handler(testCase.request) + if err != testCase.expectedError { + t.Errorf("Expected error %v, but got %v", testCase.expectedError, err) + } + + if response.Body != testCase.expectedBody { + t.Errorf("Expected response %v, but got %v", testCase.expectedBody, response.Body) + } + + if response.StatusCode != 200 { + t.Errorf("Expected status code 200, but got %v", response.StatusCode) + } + }) + } +} diff --git a/al2023/go/hello-img/{{cookiecutter.project_name}}/template.yaml b/al2023/go/hello-img/{{cookiecutter.project_name}}/template.yaml new file mode 100644 index 000000000..1081c1532 --- /dev/null +++ b/al2023/go/hello-img/{{cookiecutter.project_name}}/template.yaml @@ -0,0 +1,51 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + {{ cookiecutter.project_name }} + + Sample SAM Template for {{ cookiecutter.project_name }} + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 5 + MemorySize: 128 + +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + PackageType: Image + {%- if cookiecutter.architectures.value != []%} + Architectures: + {%- for arch in cookiecutter.architectures.value %} + - {{arch}} + {%- endfor %} + {%- endif %} + Events: + CatchAll: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: GET + Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object + Variables: + PARAM1: VALUE + Metadata: + DockerTag: {{cookiecutter.runtime}}-v1 + DockerContext: ./hello-world + Dockerfile: Dockerfile + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + HelloWorldAPI: + Description: "API Gateway endpoint URL for Prod environment for First Function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + HelloWorldFunction: + Description: "First Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/al2023/go/hello/README.md b/al2023/go/hello/README.md new file mode 100644 index 000000000..d6af33a92 --- /dev/null +++ b/al2023/go/hello/README.md @@ -0,0 +1,49 @@ +# Cookiecutter SAM for golang Lambda functions + +This is a [Cookiecutter](https://github.com/audreyr/cookiecutter) template to create a Serverless App based on Serverless Application Model (SAM). + +It is important to note that you should not try to `git clone` this project but use `cookiecutter` CLI instead as ``\\{\\{cookiecutter.project_slug\\}\\}`` will be rendered based on your input and therefore all variables and files will be rendered properly. + +## Requirements + +Install `cookiecutter` command line: + +**Pip users**: + +* `pip install cookiecutter` + +**Homebrew users**: + +* `brew install cookiecutter` + +**Windows or Pipenv users**: + +* `pipenv install cookiecutter` + +**NOTE**: [`Pipenv`](https://github.com/pypa/pipenv) is the new and recommended Python packaging tool that works across multiple platforms and makes Windows a first-class citizen. + +## Usage + +Generate a new SAM based Serverless App: `cookiecutter gh:aws-samples/cookiecutter-aws-sam-golang`. + +You'll be prompted a few questions to help this cookiecutter template to scaffold this project and after its completed you should see a new folder at your current path with the name of the project you gave as input. + +**NOTE**: After you understand how cookiecutter works (cookiecutter.json, mainly), you can fork this repo and apply your own mechanisms to accelerate your development process and this can be followed for any programming language and OS. + +## Options + +Option | Description +------------------------------------------------- | --------------------------------------------------------------------------------- +`include_apigw` | Includes sample code for API Gateway Proxy integration for Lambda and a Catch All method in SAM as a starting point +`include_xray` | Includes both sample code for getting started with AWS X-Ray and adds necessary permission and `Tracing` to your function +`include_safe_deployment` | Sends by default 10% of traffic for every 1 minute to a newly deployed function using [CodeDeploy + SAM integration](https://github.com/awslabs/serverless-application-model/blob/master/docs/safe_lambda_deployments.rst) - Linear10PercentEvery1Minute +`include_experimental_make` | Includes a `Makefile` for advanced users to automate packaging, build, tests and SAM Local - Only works on OSX/Linux at the moment + +## Credits + +* This project has been generated with [Cookiecutter](https://github.com/audreyr/cookiecutter) +* [Bruno Alla's Lambda function template](https://github.com/browniebroke/cookiecutter-lambda-function) + +## License + +This project is licensed under the terms of the [MIT License with no attribution](/LICENSE) \ No newline at end of file diff --git a/al2023/go/hello/__init__.py b/al2023/go/hello/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/al2023/go/hello/cookiecutter.json b/al2023/go/hello/cookiecutter.json new file mode 100644 index 000000000..b0c99545e --- /dev/null +++ b/al2023/go/hello/cookiecutter.json @@ -0,0 +1,13 @@ +{ + "project_name": "Name of the project", + "runtime": "provided.al2023", + "architectures": { + "value": [ + "x86_64", + "arm64" + ] + }, + "_copy_without_render": [ + ".gitignore" + ] +} \ No newline at end of file diff --git a/al2023/go/hello/requirements-dev.txt b/al2023/go/hello/requirements-dev.txt new file mode 100644 index 000000000..aa7117612 --- /dev/null +++ b/al2023/go/hello/requirements-dev.txt @@ -0,0 +1,4 @@ +cookiecutter==2.1.1 +flake8==3.5.0 +pytest==3.3.2 +pytest-cookies==0.3.0 diff --git a/al2023/go/hello/tests/__init__.py b/al2023/go/hello/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/al2023/go/hello/tests/test_bake_project.py b/al2023/go/hello/tests/test_bake_project.py new file mode 100644 index 000000000..d19187d2e --- /dev/null +++ b/al2023/go/hello/tests/test_bake_project.py @@ -0,0 +1,78 @@ +from contextlib import contextmanager + +import os + + +@contextmanager +def inside_dir(dirpath): + """ + Execute code from inside the given directory + :param dirpath: String, path of the directory the command is being run. + """ + old_path = os.getcwd() + try: + os.chdir(dirpath) + yield + finally: + os.chdir(old_path) + + +def test_project_tree(cookies): + result = cookies.bake(extra_context={'project_name': 'test_project'}) + assert result.exit_code == 0 + assert result.exception is None + assert result.project.basename == 'test_project' + + assert result.project.isdir() + assert result.project.join('README.md').isfile() + assert result.project.join('template.yaml').isfile() + assert result.project.join('hello-world').isdir() + assert result.project.join('hello-world', 'main.go').isfile() + assert result.project.join('hello-world', 'main_test.go').isfile() + + +def test_app_content(cookies): + result = cookies.bake(extra_context={'project_name': 'test_project'}) + app_file = result.project.join('hello-world', 'main.go') + app_content = app_file.readlines() + app_content = ''.join(app_content) + + contents = ( + "github.com/aws/aws-lambda-go/events", + "sourceIP := request.RequestContext.Identity.SourceIP", + "lambda.Start(handler)" + ) + + for content in contents: + assert content in app_content + + +def test_app_test_content(cookies): + result = cookies.bake(extra_context={'project_name': 'test_project'}) + app_file = result.project.join('hello-world', 'main_test.go') + app_content = app_file.readlines() + app_content = ''.join(app_content) + + contents = ( + "func TestHandler(t *testing.T)", + "SourceIP: \"127.0.0.1\"", + "response, err := handler(testCase.request)" + ) + + for content in contents: + assert content in app_content + + +def test_app_template_content(cookies): + result = cookies.bake(extra_context={'project_name': 'test_project'}) + app_file = result.project.join('template.yaml') + app_content = app_file.readlines() + app_content = ''.join(app_content) + + contents = ( + "Runtime: go1.x", + "HelloWorldFunction", + ) + + for content in contents: + assert content in app_content diff --git a/al2023/go/hello/{{cookiecutter.project_name}}/Makefile b/al2023/go/hello/{{cookiecutter.project_name}}/Makefile new file mode 100644 index 000000000..a6699b6e8 --- /dev/null +++ b/al2023/go/hello/{{cookiecutter.project_name}}/Makefile @@ -0,0 +1,4 @@ +.PHONY: build + +build: + sam build diff --git a/al2023/go/hello/{{cookiecutter.project_name}}/README.md b/al2023/go/hello/{{cookiecutter.project_name}}/README.md new file mode 100644 index 000000000..488bec19b --- /dev/null +++ b/al2023/go/hello/{{cookiecutter.project_name}}/README.md @@ -0,0 +1,141 @@ +# {{ cookiecutter.project_name }} + +This is a sample template for {{ cookiecutter.project_name }} - Below is a brief explanation of what we have generated for you: + +```bash +. +├── Makefile <-- Make to automate build +├── README.md <-- This instructions file +├── hello-world <-- Source code for a lambda function +│ ├── main.go <-- Lambda function code +│ └── main_test.go <-- Unit tests +└── template.yaml +``` + +## Requirements + +* AWS CLI already configured with Administrator permission +* [Docker installed](https://www.docker.com/community-edition) +* [Golang](https://golang.org) +* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) + +## Setup process + +### Installing dependencies & building the target + +In this example we use the built-in `sam build` to automatically download all the dependencies and package our build target. +Read more about [SAM Build here](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-build.html) + +The `sam build` command is wrapped inside of the `Makefile`. To execute this simply run + +```shell +make +``` + +### Local development + +**Invoking function locally through local API Gateway** + +```bash +sam local start-api +``` + +If the previous command ran successfully you should now be able to hit the following local endpoint to invoke your function `http://localhost:3000/hello` + +**SAM CLI** is used to emulate both Lambda and API Gateway locally and uses our `template.yaml` to understand how to bootstrap this environment (runtime, where the source code is, etc.) - The following excerpt is what the CLI will read in order to initialize an API and its routes: + +```yaml +... +Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get +``` + +## Packaging and deployment + +AWS Lambda Golang runtime requires a flat folder with the executable generated on build step. SAM will use `CodeUri` property to know where to look up for the application: + +```yaml +... + FirstFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: hello_world/ + ... +``` + +To deploy your application for the first time, run the following in your shell: + +```bash +sam deploy --guided +``` + +The command will package and deploy your application to AWS, with a series of prompts: + +* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. +* **AWS Region**: The AWS region you want to deploy your app to. +* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. +* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. +* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. + +You can find your API Gateway Endpoint URL in the output values displayed after deployment. + +### Testing + +We use `testing` package that is built-in in Golang and you can simply run the following command to run our tests: + +```shell +cd ./hello-world/ +go test -v . +``` +# Appendix + +### Golang installation + +Please ensure Go 1.x (where 'x' is the latest version) is installed as per the instructions on the official golang website: https://golang.org/doc/install + +A quickstart way would be to use Homebrew, chocolatey or your linux package manager. + +#### Homebrew (Mac) + +Issue the following command from the terminal: + +```shell +brew install golang +``` + +If it's already installed, run the following command to ensure it's the latest version: + +```shell +brew update +brew upgrade golang +``` + +#### Chocolatey (Windows) + +Issue the following command from the powershell: + +```shell +choco install golang +``` + +If it's already installed, run the following command to ensure it's the latest version: + +```shell +choco upgrade golang +``` + +## Bringing to the next level + +Here are a few ideas that you can use to get more acquainted as to how this overall process works: + +* Create an additional API resource (e.g. /hello/{proxy+}) and return the name requested through this new path +* Update unit test to capture that +* Package & Deploy + +Next, you can use the following resources to know more about beyond hello world samples and how others structure their Serverless applications: + +* [AWS Serverless Application Repository](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/al2023/go/hello/{{cookiecutter.project_name}}/events/event.json b/al2023/go/hello/{{cookiecutter.project_name}}/events/event.json new file mode 100644 index 000000000..a429ac5e5 --- /dev/null +++ b/al2023/go/hello/{{cookiecutter.project_name}}/events/event.json @@ -0,0 +1,63 @@ +{ + "body": "{\"message\": \"hello world\"}", + "resource": "/hello", + "path": "/hello", + "httpMethod": "GET", + "isBase64Encoded": false, + "queryStringParameters": { + "foo": "bar" + }, + "pathParameters": { + "proxy": "/path/to/resource" + }, + "stageVariables": { + "baz": "qux" + }, + "headers": { + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Accept-Encoding": "gzip, deflate, sdch", + "Accept-Language": "en-US,en;q=0.8", + "Cache-Control": "max-age=0", + "CloudFront-Forwarded-Proto": "https", + "CloudFront-Is-Desktop-Viewer": "true", + "CloudFront-Is-Mobile-Viewer": "false", + "CloudFront-Is-SmartTV-Viewer": "false", + "CloudFront-Is-Tablet-Viewer": "false", + "CloudFront-Viewer-Country": "US", + "Host": "1234567890.execute-api.us-east-1.amazonaws.com", + "Upgrade-Insecure-Requests": "1", + "User-Agent": "Custom User Agent String", + "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", + "X-Forwarded-For": "127.0.0.1, 127.0.0.2", + "X-Forwarded-Port": "443", + "X-Forwarded-Proto": "https" + }, + "requestContext": { + "accountId": "123456789012", + "resourceId": "123456", + "stage": "prod", + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "requestTime": "09/Apr/2015:12:34:56 +0000", + "requestTimeEpoch": 1428582896000, + "identity": { + "cognitoIdentityPoolId": null, + "accountId": null, + "cognitoIdentityId": null, + "caller": null, + "accessKey": null, + "sourceIp": "127.0.0.1", + "cognitoAuthenticationType": null, + "cognitoAuthenticationProvider": null, + "userArn": null, + "userAgent": "Custom User Agent String", + "user": null + }, + "path": "/prod/hello", + "resourcePath": "/hello", + "httpMethod": "POST", + "apiId": "1234567890", + "protocol": "HTTP/1.1" + } + } + \ No newline at end of file diff --git a/al2023/go/hello/{{cookiecutter.project_name}}/hello-world/go.mod b/al2023/go/hello/{{cookiecutter.project_name}}/hello-world/go.mod new file mode 100644 index 000000000..32da1ab76 --- /dev/null +++ b/al2023/go/hello/{{cookiecutter.project_name}}/hello-world/go.mod @@ -0,0 +1,7 @@ +require github.com/aws/aws-lambda-go v1.36.1 + +replace gopkg.in/yaml.v2 => gopkg.in/yaml.v2 v2.2.8 + +module hello-world + +go 1.16 diff --git a/al2023/go/hello/{{cookiecutter.project_name}}/hello-world/go.sum b/al2023/go/hello/{{cookiecutter.project_name}}/hello-world/go.sum new file mode 100644 index 000000000..d1ee29f48 --- /dev/null +++ b/al2023/go/hello/{{cookiecutter.project_name}}/hello-world/go.sum @@ -0,0 +1,13 @@ +github.com/aws/aws-lambda-go v1.36.1 h1:CJxGkL9uKszIASRDxzcOcLX6juzTLoTKtCIgUGcTjTU= +github.com/aws/aws-lambda-go v1.36.1/go.mod h1:jwFe2KmMsHmffA1X2R09hH6lFzJQxzI8qK17ewzbQMM= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/al2023/go/hello/{{cookiecutter.project_name}}/hello-world/main.go b/al2023/go/hello/{{cookiecutter.project_name}}/hello-world/main.go new file mode 100644 index 000000000..55d93a3da --- /dev/null +++ b/al2023/go/hello/{{cookiecutter.project_name}}/hello-world/main.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + + "github.com/aws/aws-lambda-go/events" + "github.com/aws/aws-lambda-go/lambda" +) + +func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { + var greeting string + sourceIP := request.RequestContext.Identity.SourceIP + + if sourceIP == "" { + greeting = "Hello, world!\n" + } else { + greeting = fmt.Sprintf("Hello, %s!\n", sourceIP) + } + + return events.APIGatewayProxyResponse{ + Body: greeting, + StatusCode: 200, + }, nil +} + +func main() { + lambda.Start(handler) +} diff --git a/al2023/go/hello/{{cookiecutter.project_name}}/hello-world/main_test.go b/al2023/go/hello/{{cookiecutter.project_name}}/hello-world/main_test.go new file mode 100644 index 000000000..b69105174 --- /dev/null +++ b/al2023/go/hello/{{cookiecutter.project_name}}/hello-world/main_test.go @@ -0,0 +1,60 @@ +package main + +import ( + "testing" + + "github.com/aws/aws-lambda-go/events" +) + +func TestHandler(t *testing.T) { + testCases := []struct { + name string + request events.APIGatewayProxyRequest + expectedBody string + expectedError error + }{ + { + // mock a request with an empty SourceIP + name: "empty IP", + request: events.APIGatewayProxyRequest{ + RequestContext: events.APIGatewayProxyRequestContext{ + Identity: events.APIGatewayRequestIdentity{ + SourceIP: "", + }, + }, + }, + expectedBody: "Hello, world!\n", + expectedError: nil, + }, + { + // mock a request with a localhost SourceIP + name: "localhost IP", + request: events.APIGatewayProxyRequest{ + RequestContext: events.APIGatewayProxyRequestContext{ + Identity: events.APIGatewayRequestIdentity{ + SourceIP: "127.0.0.1", + }, + }, + }, + expectedBody: "Hello, 127.0.0.1!\n", + expectedError: nil, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + response, err := handler(testCase.request) + if err != testCase.expectedError { + t.Errorf("Expected error %v, but got %v", testCase.expectedError, err) + } + + if response.Body != testCase.expectedBody { + t.Errorf("Expected response %v, but got %v", testCase.expectedBody, response.Body) + } + + if response.StatusCode != 200 { + t.Errorf("Expected status code 200, but got %v", response.StatusCode) + } + }) + } +} diff --git a/al2023/go/hello/{{cookiecutter.project_name}}/template.yaml b/al2023/go/hello/{{cookiecutter.project_name}}/template.yaml new file mode 100644 index 000000000..a39be79fb --- /dev/null +++ b/al2023/go/hello/{{cookiecutter.project_name}}/template.yaml @@ -0,0 +1,51 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + {{ cookiecutter.project_name }} + + Sample SAM Template for {{ cookiecutter.project_name }} + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 5 + MemorySize: 128 + +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Metadata: + BuildMethod: go1.x + Properties: + CodeUri: hello-world/ + Handler: bootstrap + Runtime: provided.al2023 + {%- if cookiecutter.architectures.value != []%} + Architectures: + {%- for arch in cookiecutter.architectures.value %} + - {{arch}} + {%- endfor %} + {%- endif %} + Events: + CatchAll: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: GET + Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object + Variables: + PARAM1: VALUE + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + HelloWorldAPI: + Description: "API Gateway endpoint URL for Prod environment for First Function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + HelloWorldFunction: + Description: "First Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/al2023/rust/hello/.gitignore b/al2023/rust/hello/.gitignore new file mode 100644 index 000000000..4de989e43 --- /dev/null +++ b/al2023/rust/hello/.gitignore @@ -0,0 +1,18 @@ +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +.aws-sam +build +samconfig.toml \ No newline at end of file diff --git a/al2023/rust/hello/cookiecutter.json b/al2023/rust/hello/cookiecutter.json new file mode 100644 index 000000000..c1aa95e9f --- /dev/null +++ b/al2023/rust/hello/cookiecutter.json @@ -0,0 +1,12 @@ +{ + "project_name": "My Project", + "project_slug": "{{ cookiecutter.project_name.lower().replace(' ', '-') }}", + "architectures": { + "value": [ + "x86_64" + ] + }, + "_copy_without_render": [ + ".gitignore" + ] +} \ No newline at end of file diff --git a/al2023/rust/hello/{{ cookiecutter.project_slug }}/.gitignore b/al2023/rust/hello/{{ cookiecutter.project_slug }}/.gitignore new file mode 100644 index 000000000..2cc7f784a --- /dev/null +++ b/al2023/rust/hello/{{ cookiecutter.project_slug }}/.gitignore @@ -0,0 +1,223 @@ +# Created by https://www.toptal.com/developers/gitignore/api/rust,osx,linux,windows,pycharm,visualstudiocode +# Edit at https://www.toptal.com/developers/gitignore?templates=rust,osx,linux,windows,pycharm,visualstudiocode + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### OSX ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### PyCharm ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### PyCharm Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Rust ### +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# End of https://www.toptal.com/developers/gitignore/api/rust,osx,linux,windows,pycharm,visualstudiocode + diff --git a/al2023/rust/hello/{{ cookiecutter.project_slug }}/README.md b/al2023/rust/hello/{{ cookiecutter.project_slug }}/README.md new file mode 100644 index 000000000..99763d652 --- /dev/null +++ b/al2023/rust/hello/{{ cookiecutter.project_slug }}/README.md @@ -0,0 +1,128 @@ +# {{ cookiecutter.project_name }} + +This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders: + +- `rust_app/Cargo.toml` - Project configuration file. +- `rust_app/src/main.rs` - Code for the application's Lambda function. +- `template.yaml` - A template that defines the application's AWS resources. + +The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. + +If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. +The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started. + +* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [GoLand](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [DataGrip](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html) +* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html) + + +## Requirements +* This template was tested with Rust v1.66.0 and above. + +## Deploy the sample application + +To deploy the application, you need the folllowing tools: + +* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) +* [Rust](https://www.rust-lang.org/) version 1.64.0 or newer +* [cargo-lambda](https://github.com/cargo-lambda/cargo-lambda) for cross-compilation + +To build and deploy your application for the first time, run the following in your shell: + +```bash +sam build +sam deploy +``` + +The first command will build the source of your application. The second command will package and deploy your application to AWS with the default `samconfig.toml` in the project. Alternatively, you can run `sam deploy --guided` to deploy with a series of prompts: + +* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. +* **AWS Region**: The AWS region you want to deploy your app to. +* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. +* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. +* **Save arguments to `samconfig.toml`**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. + +You can find your API Gateway Endpoint URL in the output values displayed after deployment. + +## Use the SAM CLI to build and test locally + +Build your application with the `sam build` command. + +```bash +{{ cookiecutter.project_name }}$ sam build +``` + +The SAM CLI builds the Rust app based on `rust_app/Cargo.toml`, creates a deployment package, and saves it in the `.aws-sam/build` folder. + +Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project. + +Run functions locally and invoke them with the `sam local invoke` command. + +```bash +{{ cookiecutter.project_name }}$ sam local invoke HelloWorldFunction --event events/event.json +``` + +The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000. + +```bash +{{ cookiecutter.project_name }}$ sam local start-api +{{ cookiecutter.project_name }}$ curl http://localhost:3000/ +``` + +The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path. + +```yaml + Events: + HelloWorld: + Type: Api + Properties: + Path: /hello + Method: get +``` + +## Add a resource to your application +The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types. + +## Fetch, tail, and filter Lambda function logs + +To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug. + +`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM. + +```bash +{{ cookiecutter.project_name }}$ sam logs -n HelloWorldFunction --stack-name {{ cookiecutter.project_name }} --tail +``` + +You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). + +## Tests + +Tests are defined alongside your lambda function code in the `rust_app/src` folder. + +```bash +cargo test +``` + + +## Cleanup + +To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following: + +```bash +sam delete +``` + +## Resources + +See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts. + +Next, you can use AWS Serverless Application Repository to deploy ready-to-use apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/). diff --git a/al2023/rust/hello/{{ cookiecutter.project_slug }}/events/event.json b/al2023/rust/hello/{{ cookiecutter.project_slug }}/events/event.json new file mode 100644 index 000000000..0956a139e --- /dev/null +++ b/al2023/rust/hello/{{ cookiecutter.project_slug }}/events/event.json @@ -0,0 +1,62 @@ +{ + "body": "hello world", + "resource": "/{proxy+}", + "path": "/path/to/resource", + "httpMethod": "POST", + "isBase64Encoded": false, + "queryStringParameters": { + "foo": "bar" + }, + "pathParameters": { + "proxy": "/path/to/resource" + }, + "stageVariables": { + "baz": "qux" + }, + "headers": { + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Accept-Encoding": "gzip, deflate, sdch", + "Accept-Language": "en-US,en;q=0.8", + "Cache-Control": "max-age=0", + "CloudFront-Forwarded-Proto": "https", + "CloudFront-Is-Desktop-Viewer": "true", + "CloudFront-Is-Mobile-Viewer": "false", + "CloudFront-Is-SmartTV-Viewer": "false", + "CloudFront-Is-Tablet-Viewer": "false", + "CloudFront-Viewer-Country": "US", + "Host": "1234567890.execute-api.us-east-1.amazonaws.com", + "Upgrade-Insecure-Requests": "1", + "User-Agent": "Custom User Agent String", + "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", + "X-Forwarded-For": "127.0.0.1, 127.0.0.2", + "X-Forwarded-Port": "443", + "X-Forwarded-Proto": "https" + }, + "requestContext": { + "accountId": "123456789012", + "resourceId": "123456", + "stage": "prod", + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "requestTime": "09/Apr/2015:12:34:56 +0000", + "requestTimeEpoch": 1428582896000, + "identity": { + "cognitoIdentityPoolId": null, + "accountId": null, + "cognitoIdentityId": null, + "caller": null, + "accessKey": null, + "sourceIp": "127.0.0.1", + "cognitoAuthenticationType": null, + "cognitoAuthenticationProvider": null, + "userArn": null, + "userAgent": "Custom User Agent String", + "user": null + }, + "path": "/prod/path/to/resource", + "resourcePath": "/{proxy+}", + "httpMethod": "POST", + "apiId": "1234567890", + "protocol": "HTTP/1.1" + } +} \ No newline at end of file diff --git a/al2023/rust/hello/{{ cookiecutter.project_slug }}/rust_app/Cargo.toml b/al2023/rust/hello/{{ cookiecutter.project_slug }}/rust_app/Cargo.toml new file mode 100644 index 000000000..8456c4d67 --- /dev/null +++ b/al2023/rust/hello/{{ cookiecutter.project_slug }}/rust_app/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "{{ cookiecutter.project_slug }}" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] + +lambda_runtime = "0.6.0" +serde = "1.0.136" +tokio = { version = "1", features = ["macros"] } +tracing = { version = "0.1", features = ["log"] } +tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] } diff --git a/al2023/rust/hello/{{ cookiecutter.project_slug }}/rust_app/src/main.rs b/al2023/rust/hello/{{ cookiecutter.project_slug }}/rust_app/src/main.rs new file mode 100644 index 000000000..9c54f6a44 --- /dev/null +++ b/al2023/rust/hello/{{ cookiecutter.project_slug }}/rust_app/src/main.rs @@ -0,0 +1,49 @@ +use lambda_runtime::{run, service_fn, Error, LambdaEvent}; + +use serde::{Deserialize, Serialize}; + +/// This is a made-up example. Requests come into the runtime as unicode +/// strings in json format, which can map to any structure that implements `serde::Deserialize` +/// The runtime pays no attention to the contents of the request payload. +#[derive(Deserialize)] +struct Request { +} + +/// This is a made-up example of what a response structure may look like. +/// There is no restriction on what it can be. The runtime requires responses +/// to be serialized into json. The runtime pays no attention +/// to the contents of the response payload. +#[derive(Serialize)] +struct Response { + statusCode: i32, + body: String, +} + +/// This is the main body for the function. +/// Write your code inside it. +/// There are some code example in the following URLs: +/// - https://github.com/awslabs/aws-lambda-rust-runtime/tree/main/examples +/// - https://github.com/aws-samples/serverless-rust-demo/ +async fn function_handler(event: LambdaEvent) -> Result { + // Prepare the response + let resp = Response { + statusCode: 200, + body: "Hello World!".to_string(), + }; + + // Return `Response` (it will be serialized to JSON automatically by the runtime) + Ok(resp) +} + +#[tokio::main] +async fn main() -> Result<(), Error> { + tracing_subscriber::fmt() + .with_max_level(tracing::Level::INFO) + // disable printing the name of the module in every log line. + .with_target(false) + // disabling time is handy because CloudWatch will add the ingestion time. + .without_time() + .init(); + + run(service_fn(function_handler)).await +} \ No newline at end of file diff --git a/al2023/rust/hello/{{ cookiecutter.project_slug }}/template.yaml b/al2023/rust/hello/{{ cookiecutter.project_slug }}/template.yaml new file mode 100644 index 000000000..ecea0a9db --- /dev/null +++ b/al2023/rust/hello/{{ cookiecutter.project_slug }}/template.yaml @@ -0,0 +1,49 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + {{ cookiecutter.project_name }} + + Sample SAM Template for {{ cookiecutter.project_name }} + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 3 + MemorySize: 128 + + +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Metadata: + BuildMethod: rust-cargolambda # More info about Cargo Lambda: https://github.com/cargo-lambda/cargo-lambda + Properties: + CodeUri: ./rust_app # Points to dir of Cargo.toml + Handler: bootstrap # Do not change, as this is the default executable name produced by Cargo Lambda + Runtime: provided.al2023 + {%- if cookiecutter.architectures.value != []%} + Architectures: + {%- for arch in cookiecutter.architectures.value %} + - {{arch}} + {%- endfor %} + {%- endif %} + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + HelloWorldApi: + Description: "API Gateway endpoint URL for Prod stage for Hello World function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + HelloWorldFunction: + Description: "Hello World Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/manifest-v2.json b/manifest-v2.json index 6c14bad60..c0129d9bf 100644 --- a/manifest-v2.json +++ b/manifest-v2.json @@ -197,6 +197,16 @@ "useCaseName": "Lambda Response Streaming" } ], + "go (provided.al2023)": [ + { + "directory": "al2023/go/hello", + "displayName": "Hello World Example", + "dependencyManager": "mod", + "appTemplate": "hello-world", + "packageType": "Zip", + "useCaseName": "Hello World Example" + } + ], "java8": [ { "directory": "java8/hello-gradle", @@ -1228,6 +1238,16 @@ "useCaseName": "DynamoDB Example" } ], + "rust (provided.al2023)": [ + { + "directory": "al2023/rust/hello", + "displayName": "Hello World Example", + "dependencyManager": "cargo", + "appTemplate": "hello-world", + "packageType": "Zip", + "useCaseName": "Hello World Example" + } + ], "amazon/nodejs14.x-base": [ { "directory": "nodejs14.x/hello-img", @@ -1446,6 +1466,16 @@ "useCaseName": "Hello World Example" } ], + "amazon/go-provided.al2023-base": [ + { + "directory": "al2023/go/hello-img", + "displayName": "Hello World Lambda Image Example", + "dependencyManager": "mod", + "appTemplate": "hello-world-lambda-image", + "packageType": "Image", + "useCaseName": "Hello World Example" + } + ], "amazon/java17-base": [ { "directory": "java17/hello-img-gradle", @@ -1538,4 +1568,4 @@ "useCaseName": "Hello World Example" } ] -} +} \ No newline at end of file diff --git a/tests/integration/build_invoke/test_build_invoke_go1_x.py b/tests/integration/build_invoke/test_build_invoke_go1_x.py index 612ec5c17..58fd76c69 100644 --- a/tests/integration/build_invoke/test_build_invoke_go1_x.py +++ b/tests/integration/build_invoke/test_build_invoke_go1_x.py @@ -20,6 +20,10 @@ class BuildInvoke_provided_go_cookiecutter_aws_sam_hello_golang(BuildInvokeBase. use_container = False directory = "al2/go/hello" +class BuildInvoke_providedal2023_go_cookiecutter_aws_sam_hello_golang(BuildInvokeBase.BuildInvokeBase): + use_container = False + directory = "al2023/go/hello" + class BuildInvoke_go1_x_cookiecutter_aws_sam_eventbridge_hello_golang(BuildInvokeBase.BuildInvokeBase): use_container = False directory = "go1.x/event-bridge" @@ -62,3 +66,6 @@ class BuildInvoke_image_go1_x_cookiecutter_aws_sam_hello_golang_lambda_image(Bui class BuildInvoke_image_provided_go_cookiecutter_aws_sam_hello_golang_lambda_image(BuildInvokeBase.BuildInvokeBase): directory = "al2/go/hello-img" + +class BuildInvoke_image_providedal2023_go_cookiecutter_aws_sam_hello_golang_lambda_image(BuildInvokeBase.BuildInvokeBase): + directory = "al2023/go/hello-img" \ No newline at end of file diff --git a/tests/integration/build_invoke/test_build_invoke_rust.py b/tests/integration/build_invoke/test_build_invoke_rust.py index d77658c5b..97261fd6f 100644 --- a/tests/integration/build_invoke/test_build_invoke_rust.py +++ b/tests/integration/build_invoke/test_build_invoke_rust.py @@ -16,6 +16,11 @@ class BuildInvoke_provided_rust_cookiecutter_aws_sam_hello(BuildInvokeBase.Build directory = "al2/rust/hello" beta_features = True +class BuildInvoke_providedal2023_rust_cookiecutter_aws_sam_hello(BuildInvokeBase.BuildInvokeBase): + use_container = False + directory = "al2023/rust/hello" + beta_features = True + class BuildInvoke_provided_rust_cookiecutter_aws_sam_hello_dynamodb(BuildInvokeBase.BuildInvokeBase): use_container = False directory = "al2/rust/hello-ddb" diff --git a/tests/integration/unit_test/test_unit_test_go1_x.py b/tests/integration/unit_test/test_unit_test_go1_x.py index 60c3ae168..b432490ed 100644 --- a/tests/integration/unit_test/test_unit_test_go1_x.py +++ b/tests/integration/unit_test/test_unit_test_go1_x.py @@ -10,6 +10,10 @@ class UnitTest_provided_go_cookiecutter_aws_sam_hello_golang(UnitTestBase.GoUnit directory = "al2/go/hello" code_directories = ["hello-world"] +class UnitTest_providedal2023_go_cookiecutter_aws_sam_hello_golang(UnitTestBase.GoUnitTestBase): + directory = "al2023/go/hello" + code_directories = ["hello-world"] + class UnitTest_go1_x_cookiecutter_aws_sam_eventbridge_hello_golang(UnitTestBase.GoUnitTestBase): directory = "go1.x/event-bridge" code_directories = ["hello-world"] diff --git a/tests/integration/unit_test/test_unit_test_rust.py b/tests/integration/unit_test/test_unit_test_rust.py index 3d65192bc..c057485d8 100644 --- a/tests/integration/unit_test/test_unit_test_rust.py +++ b/tests/integration/unit_test/test_unit_test_rust.py @@ -3,3 +3,6 @@ class UnitTest_rust_cookiecutter_aws_sam_hello_rust(UnitTestBase.RustUnitTestBase): directory = "al2/rust/hello" + +class UnitTest_rust_al2023_cookiecutter_aws_sam_hello_rust(UnitTestBase.RustUnitTestBase): + directory = "al2023/rust/hello"