Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project structure for Go program to run on AWS Lambda

Tags:

go

aws-lambda

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?

like image 560
Mr. 14 Avatar asked Feb 05 '18 09:02

Mr. 14


2 Answers

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.

like image 66
Mr. 14 Avatar answered Sep 29 '22 11:09

Mr. 14


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.

like image 31
Nebril Avatar answered Sep 29 '22 10:09

Nebril