1 // Copyright (C) 2024 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 std::collections::HashMap; 15 use std::fmt::Display; 16 use std::pin::Pin; 17 18 use crate::wrapper::ffi::{GetHeaders, HttpClientResponse}; 19 20 /// http client response 21 pub struct Response<'a> { 22 inner: &'a HttpClientResponse, 23 } 24 25 impl<'a> Response<'a> { 26 /// Get Response Code status(&self) -> ResponseCode27 pub fn status(&self) -> ResponseCode { 28 self.inner.GetResponseCode().try_into().unwrap_or_default() 29 } 30 headers(&self) -> HashMap<String, String>31 pub fn headers(&self) -> HashMap<String, String> { 32 let ptr = self.inner as *const HttpClientResponse as *mut HttpClientResponse; 33 let p = unsafe { Pin::new_unchecked(ptr.as_mut().unwrap()) }; 34 35 let mut headers = GetHeaders(p).into_iter(); 36 let mut ret = HashMap::new(); 37 loop { 38 if let Some(key) = headers.next() { 39 if let Some(value) = headers.next() { 40 ret.insert(key, value); 41 continue; 42 } 43 } 44 break; 45 } 46 ret 47 } 48 from_ffi(inner: &'a HttpClientResponse) -> Self49 pub(crate) fn from_ffi(inner: &'a HttpClientResponse) -> Self { 50 Self { inner } 51 } 52 } 53 54 #[derive(Clone, Debug, Default)] 55 pub enum ResponseCode { 56 #[default] 57 None = 0, 58 Ok = 200, 59 Created, 60 Accepted, 61 NotAuthoritative, 62 NoContent, 63 Reset, 64 Partial, 65 MultChoice = 300, 66 MovedPerm, 67 MovedTemp, 68 SeeOther, 69 NotModified, 70 UseProxy, 71 BadRequest = 400, 72 Unauthorized, 73 PaymentRequired, 74 Forbidden, 75 NotFound, 76 BadMethod, 77 NotAcceptable, 78 ProxyAuth, 79 ClientTimeout, 80 Conflict, 81 Gone, 82 LengthRequired, 83 PreconFailed, 84 EntityTooLarge, 85 ReqTooLong, 86 UnsupportedType, 87 InternalError = 500, 88 NotImplemented, 89 BadGateway, 90 Unavailable, 91 GatewayTimeout, 92 Version, 93 } 94 95 impl Display for ResponseCode { fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 97 let code = self.clone() as i32; 98 write!(f, "{} {:?}", code, self) 99 } 100 } 101