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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
use std::fmt;
use std::io::Read;
use url::{form_urlencoded, Url};
use crate::body::Payload;
use crate::error::ErrorKind;
use crate::header::{self, Header};
use crate::unit::{self, Unit};
use crate::Response;
use crate::{agent::Agent, error::Error};
#[cfg(feature = "json")]
use super::SerdeValue;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone)]
enum Urlish {
Url(Url),
Str(String),
}
#[derive(Clone)]
pub struct Request {
agent: Agent,
method: String,
url: Urlish,
error_on_non_2xx: bool,
headers: Vec<Header>,
query_params: Vec<(String, String)>,
}
impl fmt::Display for Urlish {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Urlish::Url(u) => write!(f, "{}", u),
Urlish::Str(s) => write!(f, "{}", s),
}
}
}
impl fmt::Debug for Request {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Request({} {} {:?}, {:?})",
self.method, self.url, self.query_params, self.headers
)
}
}
impl Request {
pub(crate) fn new(agent: Agent, method: String, url: String) -> Request {
Request {
agent,
method,
url: Urlish::Str(url),
headers: vec![],
error_on_non_2xx: true,
query_params: vec![],
}
}
pub(crate) fn with_url(agent: Agent, method: String, url: Url) -> Request {
Request {
agent,
method,
url: Urlish::Url(url),
headers: vec![],
error_on_non_2xx: true,
query_params: vec![],
}
}
pub fn call(self) -> Result<Response> {
self.do_call(Payload::Empty)
}
fn do_call(&self, payload: Payload) -> Result<Response> {
for h in &self.headers {
h.validate()?;
}
let mut url: Url = match self.url.clone() {
Urlish::Url(u) => u,
Urlish::Str(s) => s.parse().map_err(|e: url::ParseError| {
ErrorKind::InvalidUrl
.msg(&format!("failed to parse URL '{}'", self.url))
.src(e)
})?,
};
for (name, value) in self.query_params.clone() {
url.query_pairs_mut().append_pair(&name, &value);
}
let reader = payload.into_read();
let unit = Unit::new(&self.agent, &self.method, &url, &self.headers, &reader);
let response = unit::connect(unit, true, reader).map_err(|e| e.url(url.clone()))?;
if response.status() >= 400 {
Err(Error::Status(response.status(), response))
} else {
Ok(response)
}
}
#[cfg(feature = "json")]
pub fn send_json(mut self, data: SerdeValue) -> Result<Response> {
if self.header("Content-Type").is_none() {
self = self.set("Content-Type", "application/json");
}
self.do_call(Payload::JSON(data))
}
pub fn send_bytes(self, data: &[u8]) -> Result<Response> {
self.do_call(Payload::Bytes(data))
}
pub fn send_string(self, data: &str) -> Result<Response> {
let charset =
crate::response::charset_from_content_type(self.header("content-type")).to_string();
self.do_call(Payload::Text(data, charset))
}
pub fn send_form(mut self, data: &[(&str, &str)]) -> Result<Response> {
if self.header("Content-Type").is_none() {
self = self.set("Content-Type", "application/x-www-form-urlencoded");
}
let encoded = form_urlencoded::Serializer::new(String::new())
.extend_pairs(data)
.finish();
self.do_call(Payload::Bytes(&encoded.into_bytes()))
}
pub fn send(self, reader: impl Read) -> Result<Response> {
self.do_call(Payload::Reader(Box::new(reader)))
}
pub fn set(mut self, header: &str, value: &str) -> Self {
header::add_header(&mut self.headers, Header::new(header, value));
self
}
pub fn header(&self, name: &str) -> Option<&str> {
header::get_header(&self.headers, name)
}
pub fn header_names(&self) -> Vec<String> {
self.headers
.iter()
.map(|h| h.name().to_ascii_lowercase())
.collect()
}
pub fn has(&self, name: &str) -> bool {
header::has_header(&self.headers, name)
}
pub fn all(&self, name: &str) -> Vec<&str> {
header::get_all_headers(&self.headers, name)
}
pub fn query(mut self, param: &str, value: &str) -> Self {
self.query_params
.push((param.to_string(), value.to_string()));
self
}
}
#[test]
fn request_implements_send_and_sync() {
let _request: Box<dyn Send> = Box::new(Request::new(
Agent::new(),
"GET".to_string(),
"https://example.com/".to_string(),
));
let _request: Box<dyn Sync> = Box::new(Request::new(
Agent::new(),
"GET".to_string(),
"https://example.com/".to_string(),
));
}
#[test]
fn send_byte_slice() {
let bytes = vec![1, 2, 3];
crate::agent()
.post("http://example.com")
.send(&bytes[1..2])
.ok();
}