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::ErrorKind;
22 
23 /// A structure that represents an HTTP `Response`.
24 pub struct Response {
25     pub(crate) inner: Resp<HttpBody>,
26 }
27 
28 impl Response {
new(response: Resp<HttpBody>) -> Self29     pub(crate) fn new(response: Resp<HttpBody>) -> Self {
30         Self { inner: response }
31     }
32 
33     /// Reads the data of the `HttpBody`.
data(&mut self, buf: &mut [u8]) -> Result<usize, HttpClientError>34     pub async fn data(&mut self, buf: &mut [u8]) -> Result<usize, HttpClientError> {
35         Body::data(self.inner.body_mut(), buf).await
36     }
37 
38     /// Reads all the message of the `HttpBody` and return it as a `String`.
text(mut self) -> Result<String, HttpClientError>39     pub async fn text(mut self) -> Result<String, HttpClientError> {
40         let mut buf = [0u8; 1024];
41         let mut vec = Vec::new();
42         loop {
43             let size = self.data(&mut buf).await?;
44             if size == 0 {
45                 break;
46             }
47             vec.extend_from_slice(&buf[..size]);
48         }
49 
50         String::from_utf8(vec).map_err(|e| HttpClientError::from_error(ErrorKind::BodyDecode, e))
51     }
52 }
53 
54 impl Deref for Response {
55     type Target = Resp<HttpBody>;
56 
deref(&self) -> &Self::Target57     fn deref(&self) -> &Self::Target {
58         &self.inner
59     }
60 }
61 
62 impl DerefMut for Response {
deref_mut(&mut self) -> &mut Self::Target63     fn deref_mut(&mut self) -> &mut Self::Target {
64         &mut self.inner
65     }
66 }
67