

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# AWS SDK for Rust でのインターセプターの設定
<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>

1 回のオペレーションのみにインターセプターを登録するには、`customize` 拡張機能を使用します。このメソッドを使用すると、サービスクライアントの設定をオペレーション単位でオーバーライドできます。これらのカスタマイズ可能なオペレーションの詳細については、「[AWS SDK for Rust でのクライアントの 1 つのオペレーション設定の上書き](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?;
```