• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 use core::ops::{Deref, DerefMut};
15 
16 use ylong_http::body::async_impl::Body;
17 use ylong_http::response::Response as Resp;
18 
19 use crate::async_impl::HttpBody;
20 use crate::error::HttpClientError;
21 use crate::util::monitor::TimeGroup;
22 use crate::ErrorKind;
23 
24 /// A structure that represents an HTTP `Response`.
25 pub struct Response {
26     pub(crate) inner: Resp<HttpBody>,
27     pub(crate) time_group: TimeGroup,
28 }
29 
30 impl Response {
new(response: Resp<HttpBody>) -> Self31     pub(crate) fn new(response: Resp<HttpBody>) -> Self {
32         Self {
33             inner: response,
34             time_group: TimeGroup::default(),
35         }
36     }
37 
38     /// Reads the data of the `HttpBody`.
data(&mut self, buf: &mut [u8]) -> Result<usize, HttpClientError>39     pub async fn data(&mut self, buf: &mut [u8]) -> Result<usize, HttpClientError> {
40         Body::data(self.inner.body_mut(), buf).await
41     }
42 
43     /// Reads all the message of the `HttpBody` and return it as a `String`.
text(mut self) -> Result<String, HttpClientError>44     pub async fn text(mut self) -> Result<String, HttpClientError> {
45         let mut buf = [0u8; 1024];
46         let mut vec = Vec::new();
47         loop {
48             let size = self.data(&mut buf).await?;
49             if size == 0 {
50                 break;
51             }
52             vec.extend_from_slice(&buf[..size]);
53         }
54 
55         String::from_utf8(vec).map_err(|e| HttpClientError::from_error(ErrorKind::BodyDecode, e))
56     }
57 
58     /// Gets the time spent on each stage of the request.
time_group(&self) -> &TimeGroup59     pub fn time_group(&self) -> &TimeGroup {
60         &self.time_group
61     }
62 
set_time_group(&mut self, time_group: TimeGroup)63     pub(crate) fn set_time_group(&mut self, time_group: TimeGroup) {
64         self.time_group = time_group
65     }
66 }
67 
68 impl Deref for Response {
69     type Target = Resp<HttpBody>;
70 
deref(&self) -> &Self::Target71     fn deref(&self) -> &Self::Target {
72         &self.inner
73     }
74 }
75 
76 impl DerefMut for Response {
deref_mut(&mut self) -> &mut Self::Target77     fn deref_mut(&mut self) -> &mut Self::Target {
78         &mut self.inner
79     }
80 }
81