本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
注意
Rust 執行期用戶端
Amazon API Gateway API、Application Load Balancer 以及 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 執行期用戶端
注意
該 lambda_httplambda_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 事件範例
-
Lambda HTTP 事件
:處理 HTTP 事件的 Rust 函數。 -
帶有 CORS 標頭的 Lambda HTTP 事件
:使用 Tower 插入 CORS 標頭的 Rust 函數。 -
含有共用資源的 Lambda HTTP 事件
:一個 Rust 函數,它使用在建立函數處理常式之前初始化的共用資源。