Skip to content

Instantly share code, notes, and snippets.

@amoj amoj/Handler.kt
Created Mar 28, 2018

Embed
What would you like to do?
A sample Kotlin app using Spark framework in AWS Lambda.
package com.example.lambda
import com.amazonaws.serverless.exceptions.ContainerInitializationException
import com.amazonaws.serverless.proxy.model.AwsProxyRequest
import com.amazonaws.serverless.proxy.model.AwsProxyResponse
import com.amazonaws.serverless.proxy.spark.SparkLambdaContainerHandler
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.RequestHandler
import spark.Request
import spark.Response
import spark.Spark.*
class Handler @Throws(ContainerInitializationException::class)
constructor() : RequestHandler<AwsProxyRequest, AwsProxyResponse> {
private val handler = SparkLambdaContainerHandler.getAwsProxyHandler()
private var initialized = false
override fun handleRequest(request: AwsProxyRequest, context: Context?): AwsProxyResponse {
if(!initialized){
initRoutes()
initialized = true
}
return handler.proxy(request, context)
}
companion object {
@kotlin.jvm.JvmStatic
fun main(args: Array<String>){
initRoutes()
}
private fun initRoutes(){
initExceptionHandler { e ->
println("Spark initialization failed")
System.exit(100)
}
path("/greetings"){
get(""){_, _ -> "Hello World"}
get("/:name"){req, res -> greetName(
req,
res
)}
}
}
private fun greetName(req: Request, res: Response): String {
val name = req.params("name") ?: ""
return "Hello $name"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.