我已经为AWS Lambda创建了一个AWS API Gateway实例。
如何处理Lamda函数中的HTTP方法?
我的示例代码是:
class ApiGatewayHandler extends RequestHandler[Request, ApiGatewayResponse] {
def handleRequest(input: Request, context: Context): ApiGatewayResponse = {
val headers = Map("x-custom-response-header" -> "my custom response header value")
ApiGatewayResponse(200, "Go Serverless v1.0! Your function executed successfully!",
JavaConverters.mapAsJavaMap[String, Object](headers),
true)
}
}
请求类为:
class Request(@BeanProperty var key1: String, @BeanProperty var key2: String, @BeanProperty var key3: String) {
def this() = this("", "", "")
}
如何处理不同的HTTP方法?我应该使用哪些库?
答案 0 :(得分:1)
通过AWS API Gateway,您可以使用Lambda Proxy Integration将诸如HTTP方法,请求路径,标头等信息传递到AWS Lambda。
设置成功后,将库aws-lambda-java-core and aws-lambda-java-events包含到您的项目中。
在SBT中:
libraryDependencies ++= Seq(
"com.amazonaws" % "aws-lambda-java-core" % "1.2.0",
"com.amazonaws" % "aws-lambda-java-events" % "2.2.3"
)
这些是AWS的官方库,用于在Java / Scala中开发AWS Lambda函数。
此外,您将需要一个JSON处理库,例如 circe 。
在SBT中:
val circeVersion = "0.10.0"
libraryDependencies ++= Seq(
"io.circe" %% "circe-core",
"io.circe" %% "circe-generic",
"io.circe" %% "circe-parser"
).map(_ % circeVersion)
现在,您可以轻松调整Handler以使用新模型:
import scala.collection.JavaConverters._
import com.amazonaws.services.lambda.runtime.events.{APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent}
import com.amazonaws.services.lambda.runtime.{Context, RequestHandler}
import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
// TODO: Import your Request class!
object Handler extends RequestHandler[APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent] {
override def handleRequest(input: APIGatewayProxyRequestEvent, context: Context): APIGatewayProxyResponseEvent = {
def log(message: String): Unit = context.getLogger.log(message)
log("--- Received new request ---")
log(s"Method: '${input.getHttpMethod}'") // Example use of HTTP method
log(s"Proxy Path: '${input.getPath}'") // Example use of request path
val request = decode[Request](input.getBody) // Decode request using circe
request match {
case Right(req) => // TODO: Implement business logic
case Left(req) => // TODO: Implement error handling
}
val response = new APIGatewayProxyResponseEvent() // Example for a response
.withStatusCode(200)
.withHeaders(
Map(
"Content-Type" -> "text/raw",
// TODO: Add your own headers
).asJava // Convert the Scala Map to a Java Map
)
.withBody("Under construction!") // Or use circe again to encode a POJO
response // Return the response
}
}
我无法完全测试该示例,因此请务必返回可能遇到的任何问题。
顺便说一下,可以在AWS Cloudwatch中找到AWS Lambda函数将产生的日志消息。
我希望这会有所帮助。