Project structure for the Go program to run on AWS Lambda

I found the following sample code from AWS Compute Blog :

package main import ( "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { return events.APIGatewayProxyResponse{ StatusCode: 200, Body: "Hello World", }, nil } func main() { lambda.Start(handler) } 

Since lambda.Start accepts only one handler, and the entry point for the Go program is the main function, does this mean that one CodeStar project can consist of only one handler?

I understand that lambda functions should be small in size and it is preferable to process one functionality, but it seems that many projects would have to be created and it would be difficult to manage. Do I understand this correctly?

+5
source share
2 answers

Your handler function is your entry point, but since you can call it using arbitrary json data, you can have several functions called from your handler based on the data sent to the handler.

APIGatewayProxyRequest has a Body field. What you do is up to you.

The idea of ​​lambda (AFAIU) is to have minimal binaries that do only one thing. Implementing complex applications with routing requests from within the lambda seems to me an abuse of this model, but it is doable.

+3
source

Here is what I came up with so far

Project folder structure:

 project folder1 main.go folder2 main.go buildspec.yml template.yml 

buildspec.yml:

 ... build: commands: - cd folder1 - go build -o main - cd ../folder2 - go build -o main .... 

template.yml:

 .... Resources: GetTest1: Type: AWS::Serverless::Function Properties: CodeUri: ./folder1 Handler: main Runtime: go1.x Role: Fn::ImportValue: !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']] Events: GetEvent: Type: Api Properties: Path: /test1 Method: get GetTest2: Type: AWS::Serverless::Function Properties: CodeUri: ./folder2 Handler: main Runtime: go1.x Role: Fn::ImportValue: !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']] Events: GetEvent: Type: Api Properties: Path: /test2 Method: get .... 

It is important to note that all the main.go files in the subdirectories, namely folder1/main.go , folder2/main.go , must be in the package main , otherwise this will not work.

+1
source

Source: https://habr.com/ru/post/1275169/


All Articles