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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
use crate::cookie::Cookie;
use crate::Result;
use http::HeaderMap;
use reqwest::{Method, StatusCode};
use serde_json::{to_string_pretty, Value};
pub struct Response {
request_method: Method,
request_url: String,
status: StatusCode,
headers: HeaderMap,
client_cookies: Vec<Cookie>,
cookies: Vec<Cookie>,
body: Body,
}
impl From<&reqwest::cookie::Cookie<'_>> for Cookie {
fn from(val: &reqwest::cookie::Cookie) -> Self {
Cookie {
name: val.name().to_string(),
value: val.value().to_string(),
}
}
}
enum Body {
Json(Value),
Text(String),
Other,
}
impl Response {
pub(crate) async fn from_reqwest_response(
request_method: Method,
request_url: String,
client_cookies: Vec<Cookie>,
mut res: reqwest::Response,
) -> Result<Response> {
let status = res.status();
let cookies: Vec<Cookie> = res
.cookies()
.map(|c| Cookie {
name: c.name().to_string(),
value: c.value().to_string(),
})
.collect();
let headers = res.headers_mut().drain().filter_map(|(n, v)| n.map(|n| (n, v)));
let headers = HeaderMap::from_iter(headers);
let ct = headers.get("content-type").and_then(|v| v.to_str().ok());
let body = if let Some(ct) = ct {
if ct == "application/json" {
Body::Json(res.json::<Value>().await?)
} else if ct.starts_with("text/") {
Body::Text(res.text().await?)
} else {
Body::Other
}
} else {
Body::Other
};
Ok(Response {
client_cookies,
request_method,
request_url,
status,
headers,
cookies,
body,
})
}
}
impl Response {
pub async fn print(&self) -> Result<()> {
self.inner_print(true).await
}
pub async fn print_no_body(&self) -> Result<()> {
self.inner_print(false).await
}
async fn inner_print(&self, body: bool) -> Result<()> {
println!();
println!("=== Response for {} {}", self.request_method, self.request_url);
println!("=> {:<15}: {}", "Status", self.status);
println!("=> {:<15}:", "Headers");
for (n, v) in self.headers.iter() {
println!(" {n}: {v:?}");
}
if !self.cookies.is_empty() {
println!("=> {:<15}:", "Response Cookies");
for c in self.cookies.iter() {
println!(" {}: {}", c.name, c.value);
}
}
if !self.client_cookies.is_empty() {
println!("=> {:<15}:", "Client Cookies");
for c in self.client_cookies.iter() {
println!(" {}: {}", c.name, c.value);
}
}
if body {
println!("=> {:<15}:", "Response Body");
match &self.body {
Body::Json(val) => println!("{}", to_string_pretty(val)?),
Body::Text(val) => println!("{val}"),
_ => (),
}
}
println!("===\n");
Ok(())
}
}