I found the following code sample from the 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 only takes in one handler and the entry point for a Go program is the main function, does that mean one CodeStar project can only consist of one handler?
I understand that lambda functions should be small in size and preferably handle one functionality, but it seems that one would need to create a lot of projects and that would be hard to manage. Am I understanding this correctly?
Here's what I have come 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 main.go files in the subdirectories namely, folder1/main.go
, folder2/main.go
, need to be in package main
, otherwise it won't work.
Your handler
func is your entry point, but since you can call it with arbitrary json data, you can have multiple functions called from within your handler
based on the data you send to handler.
APIGatewayProxyRequest
has Body
field. What you do based on that is up to you.
The idea of lambda (AFAIU) is to have minimal binaries that do only one thing though. Implementing complex applications with request routing from within lambda seems like abusing the model to me, but it's doable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With