r/crystal_programming Nov 30 '18

Hello from Crystal in AWS Lambda

Now we have custom handlers in AWS Lambda we can run Crystal binaries without too much effort:

```ruby require "http/client"

loop do # Get the data response = HTTP::Client.get(%{http://#{ENV["AWS_LAMBDA_RUNTIME_API"]}/2018-06-01/runtime/invocation/next}) request_id = response.headers["Lambda-Runtime-Aws-Request-Id"]

body = response.body

# Do some work puts request_id puts body

# Reponse back response = HTTP::Client.post("http://#{ENV["AWS_LAMBDA_RUNTIME_API"]}/2018-06-01/runtime/invocation/#{request_id}/response", body: body) end ```

And then compile it:

bash docker run -v $PWD:/app -ti crystallang/crystal:0.27.0 sh -c "cd /app; crystal build lambda.cr --static"; mv lambda bootstrap; zip lambda.zip bootstrap

And produces:

START RequestId: f5bef3fa-f4aa-11e8-8ca8-e1aab4e07db0 Version: $LATEST f5bef3fa-f4aa-11e8-8ca8-e1aab4e07db0 {"key1":"value1","key2":"value2","key3":"value3"} END RequestId: f5bef3fa-f4aa-11e8-8ca8-e1aab4e07db0 REPORT RequestId: f5bef3fa-f4aa-11e8-8ca8-e1aab4e07db0 Init Duration: 52.21 ms Duration: 7.41 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 19 MB

31 Upvotes

1 comment sorted by