Rust での HTTP イベントの処理 - AWS Lambda

Rust での HTTP イベントの処理

注記

Rust ランタイムクライアント」は実験的なパッケージです。これは変更される可能性があり、評価のみを目的としています。

Amazon API Gateway、アプリケーションロードバランサー、および Lambda 関数 URL は、HTTP イベントを Lambda に送信できます。crates.io の aws_lambda_events クレートを使用して、これらのソースからのイベントを処理できます。

例 — API Gateway プロキシリクエストの処理

次の点に注意してください。

  • use aws_lambda_events::apigw::{ApiGatewayProxyRequest, ApiGatewayProxyResponse}: aws_lambda_events クレートには、多くの Lambda イベントが含まれています。コンパイル時間を短縮するには、機能フラグを使用して必要なイベントをアクティブにします。例えば、aws_lambda_events = { version = "0.8.3", default-features = false, features = ["apigw"] } などです。

  • use http::HeaderMap: このインポートでは、依存関係に http クレートを追加する必要があります。

use aws_lambda_events::apigw::{ApiGatewayProxyRequest, ApiGatewayProxyResponse}; use http::HeaderMap; use lambda_runtime::{service_fn, Error, LambdaEvent}; async fn handler( _event: LambdaEvent<ApiGatewayProxyRequest>, ) -> Result<ApiGatewayProxyResponse, Error> { let mut headers = HeaderMap::new(); headers.insert("content-type", "text/html".parse().unwrap()); let resp = ApiGatewayProxyResponse { status_code: 200, multi_value_headers: headers.clone(), is_base64_encoded: false, body: Some("Hello AWS Lambda HTTP request".into()), headers, }; Ok(resp) } #[tokio::main] async fn main() -> Result<(), Error> { lambda_runtime::run(service_fn(handler)).await }

また、Lambda 用の Rust ランタイムクライアントでは、これらのイベントタイプを抽象化することもでき、どのサービスがイベントを送信するかに関係なく、ネイティブ HTTP タイプを使用できます。次のコードは前の例と同等で、Lambda 関数 URL、Application Load Balancer、API Gateway ですぐに使用できます。

注記

lambda_http クレートは、その下の lambda_runtime クレートを使用します。lambda_runtime を個別にインポートする必要はありません。

例 — HTTP リクエストの処理
use lambda_http::{service_fn, Error, IntoResponse, Request, RequestExt, Response}; async fn handler(event: Request) -> Result<impl IntoResponse, Error> { let resp = Response::builder() .status(200) .header("content-type", "text/html") .body("Hello AWS Lambda HTTP request") .map_err(Box::new)?; Ok(resp) } #[tokio::main] async fn main() -> Result<(), Error> { lambda_http::run(service_fn(handler)).await }

lambda_http の使用方法の別の例については、AWS Labs GitHub リポジトリにある「http-axum コードサンプル」を参照してください。

Rust 用サンプル HTTP Lambda イベント