View a markdown version of this page

Elaborazione di eventi HTTP con Rust - AWS Lambda

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Elaborazione di eventi HTTP con Rust

Le API di Gateway Amazon API, gli Application Load Balancer e gli URL delle funzioni possono inviare eventi HTTP a Lambda. Puoi utilizzare la cassa aws_lambda_events di crates.io per elaborare gli eventi da queste origini.

Esempio- Gestione della richiesta proxy di Gateway API

Tenere presente quanto segue:

  • use aws_lambda_events::apigw::{ApiGatewayProxyRequest, ApiGatewayProxyResponse}: la cassa aws_lambda_events include molti eventi Lambda. Per ridurre i tempi di compilazione, utilizza i flag delle funzionalità per attivare gli eventi di cui hai bisogno. Esempio: aws_lambda_events = { version = "0.8.3", default-features = false, features = ["apigw"] }.

  • use http::HeaderMap: questa importazione richiede l'aggiunta della cassa http alle dipendenze.

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 }

Il client di runtime Rust per Lambda fornisce anche un'astrazione su questi tipi di eventi che puoi utilizzare con i tipi HTTP nativi, indipendentemente dal servizio che invia gli eventi. Il codice seguente è equivalente all'esempio precedente e funziona immediatamente con gli URL delle funzioni Lambda, gli Application Load Balancer e Gateway API.

Nota

La cassa lambda_http utilizza la cassa lambda_runtime sottostante. Non è necessario eseguire l'importazione di lambda_runtime separatamente.

Esempio- Gestione delle richieste 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 }

Per un altro esempio di utilizzolambda_http, consulta l'esempio di codice http-axum nel repository Labs. AWS GitHub

Eventi HTTP Lambda di esempio per Rust