Rust로 HTTP 이벤트 처리 - AWS Lambda

Rust로 HTTP 이벤트 처리

참고

Rust 런타임 클라이언트는 실험용 패키지입니다. 변경될 수 있으며 평가 목적으로만 사용됩니다.

Amazon API Gateway APIs, Application Load Balancer 및 Lambda 함수 URL에서 Lambda에 HTTP 이벤트를 전송할 수 있습니다. 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 이벤트