

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

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

Amazon API Gateway API、Application Load Balancer 以及 [Lambda 函數 URL](urls-configuration.md) 可將 HTTP 事件傳送至 Lambda。您可以使用來自 crates.io 的 [aws\$1lambda\$1events](https://crates.io/crates/aws_lambda_events) 套件來處理來自這些來源的事件。

**Example – 處理 API Gateway 代理請求**  
注意下列事項：  
+ `use aws_lambda_events::apigw::{ApiGatewayProxyRequest, ApiGatewayProxyResponse}`：[aws\$1lambda\$1events](https://crates.io/crates/aws-lambda-events) 套件包含許多 Lambda 事件。為了減少編譯時間，請使用功能標誌來激活所需的事件。範例：`aws_lambda_events = { version = "0.8.3", default-features = false, features = ["apigw"] }`。
+ `use http::HeaderMap`：此匯入要求您將 [http](https://crates.io/crates/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 執行期用戶端](https://github.com/aws/aws-lambda-rust-runtime)也提供這些事件類型的抽象表示，讓您可以使用原生 HTTP 類型，而不論是哪個服務傳送事件。下列程式碼等同於前一個範例，而且可直接使用 Lambda 函數 URL、Application Load Balancer 和 API Gateway。

**注意**  
該 [lambda\$1http](https://crates.io/crates/lambda_http) 套件使用下面的 [lambda\$1runtime](https://crates.io/crates/lambda_runtime) 套件。不必單獨匯入 `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)：處理 HTTP 事件的 Rust 函數。
+ [帶有 CORS 標頭的 Lambda HTTP 事件](https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/http-cors)：使用 Tower 插入 CORS 標頭的 Rust 函數。
+ [含有共用資源的 Lambda HTTP 事件](https://github.com/aws/aws-lambda-rust-runtime/tree/main/examples/basic-shared-resource)：一個 Rust 函數，它使用在建立函數處理常式之前初始化的共用資源。