

# 使用 Rust 处理 HTTP 事件
<a name="rust-http-events"></a>

Amazon API Gateway API、应用程序负载均衡器和 [Lambda 函数 URL](urls-configuration.md) 都可将 HTTP 事件发送到 Lambda。您可以使用 crates.io 中的 [aws\$1lambda\$1events](https://crates.io/crates/aws_lambda_events) crate 处理来自这些来源的事件。

**Example – 处理 API Gateway 代理请求**  
请注意以下几点：  
+ `use aws_lambda_events::apigw::{ApiGatewayProxyRequest, ApiGatewayProxyResponse}`：[aws\$1lambda\$1events](https://crates.io/crates/aws-lambda-events) crate 包含多个 Lambda 事件。要缩短编译时间，请使用功能标志激活所需事件。示例：`aws_lambda_events = { version = "0.8.3", default-features = false, features = ["apigw"] }`。
+ `use http::HeaderMap`：此导入要求您将 [http](https://crates.io/crates/http) crate 添加到依赖项中。

```
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 运行时系统客户端](https://github.com/aws/aws-lambda-rust-runtime)还提供对这些事件类型的抽象，允许您使用本机 HTTP 类型，无论哪个服务发送事件。以下代码等同于前面的示例，可以结合 Lambda 函数 URL、应用程序负载均衡器和 API Gateway 直接使用。

**注意**  
[lambda\$1http](https://crates.io/crates/lambda_http) crate 将使用下方的 [lambda\$1runtime](https://crates.io/crates/lambda_runtime) crate。无需单独导入 `lambda_runtime`。

**Example – 处理 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 代码示例](https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/http-axum/src/main.rs)。

**适用于 Rust 的示例 HTTP Lambda 事件**
+ [Lambda HTTP 事件](https://github.com/aws/aws-lambda-rust-runtime/tree/main/examples/http-basic-lambda)：此 Rust 函数可处理 HTTP 事件。
+ [包含 CORS 标头的 Lambda HTTP 事件](https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/http-cors)：此 Rust 函数使用 Tower 注入 CORS 标头。
+ [具有共享资源的 Lambda HTTP 事件](https://github.com/aws/aws-lambda-rust-runtime/tree/main/examples/basic-shared-resource)：此 Rust 函数使用在创建函数处理程序之前初始化的共享资源。