

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

# 在適用於 Rust 的 AWS SDK 中設定攔截器
<a name="interceptors"></a>

您可以使用攔截器來勾結 API 請求和回應的執行。攔截器是開放式機制，其中 SDK 會呼叫您寫入的程式碼，將行為注入請求/回應生命週期。如此一來，您就可以修改處理中的請求、偵錯請求處理、檢視錯誤等。

下列範例顯示簡單的攔截器，在輸入重試迴圈之前，會將額外的標頭新增至所有傳出請求：

```
use std::borrow::Cow;
use aws_smithy_runtime_api::client::interceptors::{
    Intercept,
    context::BeforeTransmitInterceptorContextMut,   
};
use aws_smithy_runtime_api::client::runtime_components::RuntimeComponents;
use aws_smithy_types::config_bag::ConfigBag;
use aws_smithy_runtime_api::box_error::BoxError;

#[derive(Debug)]
struct AddHeaderInterceptor {
    key: Cow<'static, str>,
    value: Cow<'static, str>,
}

impl AddHeaderInterceptor {
    fn new(key: &'static str, value: &'static str) -> Self {
        Self {
            key: Cow::Borrowed(key),
            value: Cow::Borrowed(value),
        }
    }
}

impl Intercept for AddHeaderInterceptor {
    fn name(&self) -> &'static str {
        "AddHeader"
    }

    fn modify_before_retry_loop(
        &self,
        context: &mut BeforeTransmitInterceptorContextMut<'_>,
        _runtime_components: &RuntimeComponents,
        _cfg: &mut ConfigBag,
    ) -> Result<(), BoxError> {
        let headers = context.request_mut().headers_mut();
        headers.insert(self.key.clone(), self.value.clone());

        Ok(())
    }
}
```

如需詳細資訊和可用的攔截器掛鉤，請參閱[攔截](https://docs.rs/aws-smithy-runtime-api/latest/aws_smithy_runtime_api/client/interceptors/trait.Intercept.html)特徵。

## 攔截器註冊
<a name="interceptors-registration"></a>

您可以在建構服務用戶端或覆寫特定操作的組態時註冊攔截器。根據您希望攔截器套用到用戶端的所有操作，還是只套用特定操作， 中的註冊會有所不同。

### 服務用戶端上所有操作的攔截器
<a name="interceptors-registration-all"></a>

若要註冊整個用戶端的攔截器，請使用 `Builder` 模式新增攔截器。

```
let config = aws_config::defaults(BehaviorVersion::latest())
    .load()
    .await;
    
// All service operations invoked using 's3' will have the header added.
let s3_conf = aws_sdk_s3::config::Builder::from(&config)
    .interceptor(AddHeaderInterceptor::new("x-foo-version", "2.7"))
    .build();

let s3 = aws_sdk_s3::Client::from_conf(s3_conf);
```

### 僅特定操作的攔截器
<a name="interceptors-registration-specific"></a>

若要僅註冊單一操作的攔截器，請使用 `customize`擴充功能。您可以使用此方法覆寫每個操作層級的服務用戶端組態。如需可自訂操作的詳細資訊，請參閱 [在適用於 Rust 的 AWS SDK 中覆寫用戶端的單一操作組態](peroperation.md)。

```
// Only the list_buckets operation will have the header added.
s3.list_buckets()
    .customize()
    .interceptor(AddHeaderInterceptor::new("x-bar-version", "3.7"))
    .send()
    .await?;
```