pub struct Response<B>(_);
Expand description

HTTP 响应

Implementations§

转换为 HTTP 响应体

Examples found in repository?
src/regions/endpoints_provider/bucket_domains_provider.rs (line 283)
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
    fn do_sync_query(&self) -> ApiResult<Endpoints> {
        let endpoints: Endpoints = self
            .queryer
            .http_client
            .get(&[ServiceName::Uc], &self.queryer.uc_endpoints)
            .path("/v2/domains")
            .authorization(Authorization::v2(&self.credential))
            .append_query_pair("tbl", self.bucket_name.as_str())
            .accept_json()
            .call()?
            .parse_json::<Vec<String>>()?
            .into_body()
            .into_iter()
            .map(Endpoint::from)
            .collect();
        Ok(endpoints)
    }

    #[cfg(feature = "async")]
    async fn do_async_query(&self) -> ApiResult<Endpoints> {
        let endpoints: Endpoints = self
            .queryer
            .http_client
            .async_get(&[ServiceName::Uc], &self.queryer.uc_endpoints)
            .path("/v2/domains")
            .authorization(Authorization::v2(&self.credential))
            .append_query_pair("tbl", self.bucket_name.as_str())
            .accept_json()
            .call()
            .await?
            .parse_json::<Vec<String>>()
            .await?
            .into_body()
            .into_iter()
            .map(Endpoint::from)
            .collect();
        Ok(endpoints)
    }

转换为 HTTP 响应信息和响应体

Examples found in repository?
src/client/call/utils.rs (line 388)
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
    fn to_status_code_error(response: SyncResponse, retried: &RetriedStatsInfo) -> ApiResult<SyncResponse> {
        let status_code = response.status_code();
        let (parts, body) = response.parse_json::<ErrorResponseBody>()?.into_parts_and_body();
        Err(
            ResponseError::new_with_msg(ResponseErrorKind::StatusCodeError(status_code), body.into_error())
                .response_parts(&parts)
                .retried(retried),
        )
    }
}

fn check_x_req_id(response: &mut SyncResponse, retried: &RetriedStatsInfo) -> ApiResult<()> {
    if response.x_reqid().is_some() {
        Ok(())
    } else {
        Err(make_malicious_response(response.parts(), retried).read_response_body_sample(response.body_mut())?)
    }
}

#[cfg(feature = "async")]
async fn async_check_x_req_id(response: &mut AsyncResponse, retried: &RetriedStatsInfo) -> ApiResult<()> {
    if response.x_reqid().is_some() {
        Ok(())
    } else {
        Err(make_malicious_response(response.parts(), retried)
            .async_read_response_body_sample(response.body_mut())
            .await?)
    }
}

fn make_malicious_response(parts: &ResponseParts, retried: &RetriedStatsInfo) -> ResponseError {
    ResponseError::new_with_msg(
        ResponseErrorKind::MaliciousResponse,
        "cannot find X-ReqId header from response, might be malicious response",
    )
    .response_parts(parts)
    .retried(retried)
}

fn make_unexpected_status_code_error(parts: &ResponseParts, retried: &RetriedStatsInfo) -> ResponseError {
    ResponseError::new_with_msg(
        ResponseErrorKind::UnexpectedStatusCode(parts.status_code()),
        format!("status code {} is unexpected", parts.status_code()),
    )
    .response_parts(parts)
    .retried(retried)
}

#[cfg(feature = "async")]
mod async_utils {
    use super::{
        super::super::{AsyncResponse, InnerRequestParts},
        *,
    };
    use qiniu_http::AsyncRequest as AsyncHttpRequest;
    use std::future::Future;

    pub(in super::super) async fn sign_async_request(
        request: &mut AsyncHttpRequest<'_>,
        authorization: Option<&Authorization<'_>>,
        retried: &RetriedStatsInfo,
    ) -> Result<(), TryError> {
        if let Some(authorization) = authorization {
            authorization
                .async_sign(request)
                .await
                .map_err(|err| handle_sign_request_error(err, retried))?;
        }
        Ok(())
    }

    pub(in super::super) async fn async_resolve(
        parts: &InnerRequestParts<'_>,
        domain_with_port: &DomainWithPort,
        extensions: &mut Extensions,
        retried: &RetriedStatsInfo,
    ) -> Result<Vec<IpAddrWithPort>, TryError> {
        let answers = with_resolve_domain(parts, domain_with_port.domain(), extensions, retried, || async {
            parts
                .http_client()
                .resolver()
                .async_resolve(
                    domain_with_port.domain(),
                    ResolveOptions::builder().retried(retried).build(),
                )
                .await
        });
        return Ok(answers
            .await?
            .into_ip_addrs()
            .iter()
            .map(|&ip| IpAddrWithPort::new(ip, domain_with_port.port()))
            .collect());

        async fn with_resolve_domain<F: FnOnce() -> Fu, Fu: Future<Output = ResolveResult>>(
            parts: &InnerRequestParts<'_>,
            domain: &str,
            extensions: &mut Extensions,
            retried: &RetriedStatsInfo,
            f: F,
        ) -> Result<ResolveAnswers, TryError> {
            call_to_resolve_domain_callbacks(parts, domain, extensions, retried)?;
            let answers = f()
                .await
                .map_err(|err| TryError::new(err, RetryDecision::TryNextServer.into()))?;
            call_domain_resolved_callbacks(parts, domain, &answers, extensions, retried)?;
            Ok(answers)
        }
    }

    pub(in super::super) async fn async_choose(
        parts: &InnerRequestParts<'_>,
        ips: &[IpAddrWithPort],
        extensions: &mut Extensions,
        retried: &RetriedStatsInfo,
    ) -> Result<Vec<IpAddrWithPort>, TryError> {
        call_to_choose_ips_callbacks(parts, ips, extensions, retried)?;
        let chosen_ips = parts
            .http_client()
            .chooser()
            .async_choose(ips, Default::default())
            .await
            .into_ip_addrs();
        call_ips_chosen_callbacks(parts, ips, &chosen_ips, extensions, retried)?;
        Ok(chosen_ips)
    }

    pub(in super::super) async fn async_judge(
        mut response: AsyncResponse,
        retried: &RetriedStatsInfo,
    ) -> ApiResult<AsyncResponse> {
        return match response.status_code().as_u16() {
            0..=199 | 300..=399 => Err(make_unexpected_status_code_error(response.parts(), retried)),
            200..=299 => {
                async_check_x_req_id(&mut response, retried).await?;
                Ok(response)
            }
            _ => to_status_code_error(response, retried).await,
        };

        async fn to_status_code_error(response: AsyncResponse, retried: &RetriedStatsInfo) -> ApiResult<AsyncResponse> {
            let status_code = response.status_code();
            let (parts, body) = response.parse_json::<ErrorResponseBody>().await?.into_parts_and_body();
            Err(
                ResponseError::new_with_msg(ResponseErrorKind::StatusCodeError(status_code), body.into_error())
                    .response_parts(&parts)
                    .retried(retried),
            )
        }
More examples
Hide additional examples
src/regions/regions_provider/bucket_regions_queryer.rs (line 319)
318
319
320
321
322
323
324
325
326
327
328
fn handle_response_body(response: Response<ResponseBody>) -> ApiResult<GotRegions> {
    let (parts, body) = response.into_parts_and_body();
    let hosts = body.into_hosts();
    let min_lifetime = hosts.iter().map(|host| host.lifetime()).min();
    let mut got_regions = hosts
        .into_iter()
        .map(|host| Region::try_from(host).map_err(|err| ResponseError::from_endpoint_parse_error(err, &parts)))
        .collect::<ApiResult<GotRegions>>()?;
    *got_regions.lifetime_mut() = min_lifetime;
    Ok(got_regions)
}
src/regions/regions_provider/all_regions_provider.rs (line 286)
285
286
287
288
289
290
291
292
293
294
295
    fn handle_response_body(response: Response<ResponseBody>) -> ApiResult<GotRegions> {
        let (parts, body) = response.into_parts_and_body();
        let hosts = body.into_hosts();
        let min_lifetime = hosts.iter().map(|host| host.lifetime()).min();
        let mut got_regions = hosts
            .into_iter()
            .map(|host| Region::try_from(host).map_err(|err| ResponseError::from_endpoint_parse_error(err, &parts)))
            .collect::<ApiResult<GotRegions>>()?;
        *got_regions.lifetime_mut() = min_lifetime;
        Ok(got_regions)
    }

根据 HTTP 响应信息和响应体创建 HTTP 响应

获取 HTTP 响应的 X-ReqId 信息

Examples found in repository?
src/client/call/utils.rs (line 398)
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
fn check_x_req_id(response: &mut SyncResponse, retried: &RetriedStatsInfo) -> ApiResult<()> {
    if response.x_reqid().is_some() {
        Ok(())
    } else {
        Err(make_malicious_response(response.parts(), retried).read_response_body_sample(response.body_mut())?)
    }
}

#[cfg(feature = "async")]
async fn async_check_x_req_id(response: &mut AsyncResponse, retried: &RetriedStatsInfo) -> ApiResult<()> {
    if response.x_reqid().is_some() {
        Ok(())
    } else {
        Err(make_malicious_response(response.parts(), retried)
            .async_read_response_body_sample(response.body_mut())
            .await?)
    }
}

获取 HTTP 响应的 X-Log 信息

解析 JSON 响应体

Examples found in repository?
src/regions/regions_provider/all_regions_provider.rs (line 265)
257
258
259
260
261
262
263
264
265
266
267
        fn do_sync_query(&self) -> ApiResult<GotRegions> {
            handle_response_body(
                self.http_client
                    .get(&[ServiceName::Uc], &self.uc_endpoints)
                    .path("/regions")
                    .authorization(Authorization::v2(&self.credential_provider))
                    .accept_json()
                    .call()?
                    .parse_json::<ResponseBody>()?,
            )
        }
More examples
Hide additional examples
src/client/call/utils.rs (line 388)
386
387
388
389
390
391
392
393
394
    fn to_status_code_error(response: SyncResponse, retried: &RetriedStatsInfo) -> ApiResult<SyncResponse> {
        let status_code = response.status_code();
        let (parts, body) = response.parse_json::<ErrorResponseBody>()?.into_parts_and_body();
        Err(
            ResponseError::new_with_msg(ResponseErrorKind::StatusCodeError(status_code), body.into_error())
                .response_parts(&parts)
                .retried(retried),
        )
    }
src/regions/regions_provider/bucket_regions_queryer.rs (line 296)
286
287
288
289
290
291
292
293
294
295
296
297
298
    fn do_sync_query(&self) -> ApiResult<GotRegions> {
        handle_response_body(
            self.queryer
                .http_client
                .get(&[ServiceName::Uc, ServiceName::Api], &self.queryer.uc_endpoints)
                .path("/v4/query")
                .append_query_pair("ak", self.access_key.as_str())
                .append_query_pair("bucket", self.bucket_name.as_str())
                .accept_json()
                .call()?
                .parse_json::<ResponseBody>()?,
        )
    }
src/regions/endpoints_provider/bucket_domains_provider.rs (line 282)
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
    fn do_sync_query(&self) -> ApiResult<Endpoints> {
        let endpoints: Endpoints = self
            .queryer
            .http_client
            .get(&[ServiceName::Uc], &self.queryer.uc_endpoints)
            .path("/v2/domains")
            .authorization(Authorization::v2(&self.credential))
            .append_query_pair("tbl", self.bucket_name.as_str())
            .accept_json()
            .call()?
            .parse_json::<Vec<String>>()?
            .into_body()
            .into_iter()
            .map(Endpoint::from)
            .collect();
        Ok(endpoints)
    }

异步解析 JSON 响应体

Examples found in repository?
src/client/call/utils.rs (line 528)
526
527
528
529
530
531
532
533
534
        async fn to_status_code_error(response: AsyncResponse, retried: &RetriedStatsInfo) -> ApiResult<AsyncResponse> {
            let status_code = response.status_code();
            let (parts, body) = response.parse_json::<ErrorResponseBody>().await?.into_parts_and_body();
            Err(
                ResponseError::new_with_msg(ResponseErrorKind::StatusCodeError(status_code), body.into_error())
                    .response_parts(&parts)
                    .retried(retried),
            )
        }
More examples
Hide additional examples
src/regions/regions_provider/all_regions_provider.rs (line 279)
270
271
272
273
274
275
276
277
278
279
280
281
282
        async fn do_async_query(&self) -> ApiResult<GotRegions> {
            handle_response_body(
                self.http_client
                    .async_get(&[ServiceName::Uc], &self.uc_endpoints)
                    .path("/regions")
                    .authorization(Authorization::v2(&self.credential_provider))
                    .accept_json()
                    .call()
                    .await?
                    .parse_json::<ResponseBody>()
                    .await?,
            )
        }
src/regions/regions_provider/bucket_regions_queryer.rs (line 312)
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    async fn do_async_query(&self) -> ApiResult<GotRegions> {
        handle_response_body(
            self.queryer
                .http_client
                .async_get(&[ServiceName::Uc, ServiceName::Api], &self.queryer.uc_endpoints)
                .path("/v4/query")
                .append_query_pair("ak", self.access_key.as_str())
                .append_query_pair("bucket", self.bucket_name.as_str())
                .accept_json()
                .call()
                .await?
                .parse_json::<ResponseBody>()
                .await?,
        )
    }
src/regions/endpoints_provider/bucket_domains_provider.rs (line 302)
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
    async fn do_async_query(&self) -> ApiResult<Endpoints> {
        let endpoints: Endpoints = self
            .queryer
            .http_client
            .async_get(&[ServiceName::Uc], &self.queryer.uc_endpoints)
            .path("/v2/domains")
            .authorization(Authorization::v2(&self.credential))
            .append_query_pair("tbl", self.bucket_name.as_str())
            .accept_json()
            .call()
            .await?
            .parse_json::<Vec<String>>()
            .await?
            .into_body()
            .into_iter()
            .map(Endpoint::from)
            .collect();
        Ok(endpoints)
    }

Methods from Deref<Target = HttpResponse<B>>§

获取 HTTP 响应体

获取 HTTP 响应体的可变引用

HTTP 响应信息

获取 HTTP 响应信息的可变引用

Methods from Deref<Target = ResponseParts>§

获取 HTTP 状态码

获取 HTTP 状态码 的可变引用

获取 HTTP Headers

获取 HTTP Headers 的可变引用

获取 HTTP 版本

获取 HTTP 版本的可变引用

获取 扩展信息

获取扩展信息的可变引用

获取 HTTP 响应 Header

获取 HTTP 服务器 IP 地址

获取 HTTP 服务器 IP 地址的可变引用

获取 HTTP 服务器端口号

获取 HTTP 服务器端口号的可变引用

获取 HTTP 响应的指标信息

获取 HTTP 响应的指标信息的可变引用

Trait Implementations§

Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
The resulting type after dereferencing.
Dereferences the value.
Mutably dereferences the value.
Converts to this type from the input type.
Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Converts self into T using Into<T>. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Pipes by value. This is generally the method you want to use. Read more
Borrows self and passes that borrow into the pipe function. Read more
Mutably borrows self and passes that borrow into the pipe function. Read more
Borrows self, then passes self.borrow() into the pipe function. Read more
Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Borrows self, then passes self.as_ref() into the pipe function.
Mutably borrows self, then passes self.as_mut() into the pipe function.
Borrows self, then passes self.deref() into the pipe function.
Mutably borrows self, then passes self.deref_mut() into the pipe function.
Should always be Self
Immutable access to a value. Read more
Mutable access to a value. Read more
Immutable access to the Borrow<B> of a value. Read more
Mutable access to the BorrowMut<B> of a value. Read more
Immutable access to the AsRef<R> view of a value. Read more
Mutable access to the AsMut<R> view of a value. Read more
Immutable access to the Deref::Target of a value. Read more
Mutable access to the Deref::Target of a value. Read more
Calls .tap() only in debug builds, and is erased in release builds.
Calls .tap_mut() only in debug builds, and is erased in release builds.
Calls .tap_borrow() only in debug builds, and is erased in release builds.
Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Calls .tap_ref() only in debug builds, and is erased in release builds.
Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Calls .tap_deref() only in debug builds, and is erased in release builds.
Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Attempts to convert self into T using TryInto<T>. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more