serverlessserverless-frameworkaws-serverlessserverless-offline

Avoid using Docker with Serverless Offline and Golang


Currently, every time I need to use serverless offline, I have to set my function handler in serverless.yml to the main.go of the function as such:

hello:
    handler: src/hello/main.go
    memorySize: 128
    timeout: 5
    events:
        - httpApi:
              path: /hello
              method: get
    iamRoleStatements:
        - Effect: 'Allow'
          Action:
              - 'dynamodb:GetItem'
          Resource: !GetAtt DeviceTable.Arn

But keeping this breaks AWS Lambda and I have to change it back to bin/hello.

A solution is to use serverless offline --useDocker but testing functions that is running in Docker takes more than 30s, which is super slow.

Is there a way around this?


Solution

  • Just compile your go code to binary files then run the serverless offline command.

    You can create a Makefile to create some alias command. ex

    .PHONY: build clean deploy deploy-local
    
    build: clean
        @env GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags="-s -w" -o bin/hello src/hello/main.go
    
    clean:
        @rm -rf ./bin
    
    deploy-local: build
        @sls offline
    
    deploy: clean build
        @sls deploy --verbose
    

    Then, you can run make deploy-local to start serverless offline server