1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use std::string::FromUtf8Error;
use base64::{prelude::BASE64_STANDARD, Engine};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Response {
pub(crate) status_code: u16,
pub(crate) url: String,
pub(crate) headers: Vec<(String, String)>,
pub(crate) body: Vec<u8>,
}
impl Response {
/// The status code (e.g. 200)
pub fn status_code(&self) -> u16 {
self.status_code
}
/// The final URL. This can differ from the request URL when redirects are followed.
pub fn url(&self) -> &str {
&self.url
}
/// The header value for the given name, or None if not found.
///
/// For historical reasons, the HTTP spec allows for header values to be encoded using encodings
/// like iso-8859-1. Such encodings mean the values are not possible to interpret as utf-8.
///
/// In case the header value can't be read as utf-8, this function also returns `None`.
pub fn header(&self, name: &str) -> Option<&str> {
for header in self.headers.iter() {
if header.0 == name {
return Some(&header.1);
}
}
None
}
/// Turns the response into a `utf-8` encoded `String`.
///
/// If the encoding fails, returns an error.
pub fn text(self) -> Result<String, FromUtf8Error> {
String::from_utf8(self.body)
}
/// Deserializes the response into a JSON value.
///
/// # Any type
///
/// ```no_run
/// use serde_json::Value;
/// use flawless_http::get;
///
/// let response = get("https://httpbin.org/get").send().unwrap();
/// let json: Value = response.json().unwrap();
///
/// assert_eq!(json["url"].as_str().unwrap(), "https://httpbin.org/get");
/// ```
///
/// # Specific type
///
/// ```no_run
/// use std::collections::HashMap;
///
/// use flawless_http::get;
///
/// #[derive(serde::Deserialize)]
/// struct BinGet {
/// args: HashMap<String, String>,
/// headers: HashMap<String, String>,
/// origin: String,
/// url: String
/// }
///
/// let response = get("https://httpbin.org/get").send().unwrap();
/// let json: BinGet = response.json().unwrap();
///
/// assert_eq!(json.url, "https://httpbin.org/get");
/// ```
#[cfg(feature = "json")]
pub fn json<T: serde::de::DeserializeOwned>(self) -> Result<T, serde_json::Error> {
serde_json::from_slice(&self.body)
}
/// Returns the raw body of a response.
pub fn body(self) -> Vec<u8> {
self.body
}
}
impl From<flawless_wasabi::HttpResponse> for Response {
fn from(value: flawless_wasabi::HttpResponse) -> Self {
let body =
BASE64_STANDARD.decode(value.body).expect("Should always be a correctly encoded base64 value");
Self { status_code: value.status_code, url: value.url, headers: value.headers, body }
}
}