Skip to content

Instantly share code, notes, and snippets.

@carlosgeos
Last active January 26, 2019 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlosgeos/14fc5e13fecd78243fba5cdbf1846c07 to your computer and use it in GitHub Desktop.
Save carlosgeos/14fc5e13fecd78243fba5cdbf1846c07 to your computer and use it in GitHub Desktop.
How to run Clojure code on AWS Lambda
(ns some-app.hello
(:gen-class
:methods [^:static [handler [String] String]])
(:require [clj-time.core :as t]))
(defn -handler [s]
(let [time_now (t/to-time-zone (t/now) (t/time-zone-for-id "Europe/Brussels")) ]
(str "Hello " s "! " "The time is now: "
(t/hour time_now) ":" (t/minute time_now))))
;; run 'lein uberjar' and upload the .jar to AWS Lambda
;; set some_app.hello::handler as the handler in the options !
;; Note about dashes and underscores:
;; Paths (folders) may have underscores
;; (ns) forms and config in project.clj should convert them to dashes
;; The minimum memory that has to be set for this to work is 192 MB (128 MB times out)
;; although the time billed increases as a side effect. 512 MB seems to work fine.
;; If input and/or response is JSON, set the param type and return type
;; to Object or some other compatible thing with JSON
(ns human-traffic.core
(:gen-class
:methods [^:static [handler [Object] Object]])
(:require [cheshire.core :as json]))
;;; Because this is on AWS Lambda + API Gateway, there is no need for
;;; any HTTP servers or routing middleware. Just fetch from DB and
;;; return JSON
;;; AWS Lambda proxy response format
;;; {
;;; "isBase64Encoded": true/false,
;;; "statusCode": 200,
;;; "headers": {},
;;; "body": "The body" ;; <-- stringified body !
;;; }
(def lambda_default
{"isBase64Encoded" false
"headers" {}
"statusCode" 200})
(defn -handler
"API Gateway transforms query GET params into POST fields, which can
be found in s"
[s]
(merge lambda_default {"body" (json/generate-string s)}))
(defproject aws-clj-lambda "0.1.0"
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/data.json "0.2.6"]
[com.amazonaws/aws-lambda-java-core "1.2.0"]
[clj-time/clj-time "0.14.2"]]
:java-source-paths ["src/java"] ;; if mixing clojure and java
:main some-app.core
:aot :all) ;; compiles other.clj as well to put it in the uberjar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment