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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
use std::borrow::Borrow;
use std::convert::{From, TryInto};
use std::fs;
use std::str;
use std::time::Duration;
use http::{
header::{
HeaderMap, HeaderValue, IntoHeaderName, ACCEPT, CONNECTION, CONTENT_LENGTH, CONTENT_TYPE, TRANSFER_ENCODING,
USER_AGENT,
},
Method,
};
use url::Url;
#[cfg(feature = "charsets")]
use crate::charsets::Charset;
use crate::error::{Error, ErrorKind, Result};
use crate::parsing::Response;
use crate::request::{
body::{self, Body, BodyKind},
header_append, header_insert, header_insert_if_missing,
proxy::ProxySettings,
BaseSettings, PreparedRequest,
};
use crate::tls::Certificate;
const DEFAULT_USER_AGENT: &str = concat!("attohttpc/", env!("CARGO_PKG_VERSION"));
#[derive(Debug)]
pub struct RequestBuilder<B = body::Empty> {
url: Url,
method: Method,
body: B,
base_settings: BaseSettings,
}
impl RequestBuilder {
pub fn new<U>(method: Method, base_url: U) -> Self
where
U: AsRef<str>,
{
Self::try_new(method, base_url).expect("invalid url or method")
}
pub fn try_new<U>(method: Method, base_url: U) -> Result<Self>
where
U: AsRef<str>,
{
Self::try_with_settings(method, base_url, BaseSettings::default())
}
pub(crate) fn with_settings<U>(method: Method, base_url: U, base_settings: BaseSettings) -> Self
where
U: AsRef<str>,
{
Self::try_with_settings(method, base_url, base_settings).expect("invalid url or method")
}
pub(crate) fn try_with_settings<U>(method: Method, base_url: U, base_settings: BaseSettings) -> Result<Self>
where
U: AsRef<str>,
{
let url = Url::parse(base_url.as_ref()).map_err(|_| ErrorKind::InvalidBaseUrl)?;
if method == Method::CONNECT {
return Err(ErrorKind::ConnectNotSupported.into());
}
Ok(Self {
url,
method,
body: body::Empty,
base_settings,
})
}
}
impl<B> RequestBuilder<B> {
pub fn param<K, V>(mut self, key: K, value: V) -> Self
where
K: AsRef<str>,
V: ToString,
{
self.url.query_pairs_mut().append_pair(key.as_ref(), &value.to_string());
self
}
pub fn params<P, K, V>(mut self, pairs: P) -> Self
where
P: IntoIterator,
P::Item: Borrow<(K, V)>,
K: AsRef<str>,
V: ToString,
{
for pair in pairs.into_iter() {
let (key, value) = pair.borrow();
self.url.query_pairs_mut().append_pair(key.as_ref(), &value.to_string());
}
self
}
#[cfg(all(
feature = "tls",
not(any(target_os = "windows", target_os = "macos", target_os = "ios"))
))]
pub fn basic_auth(self, username: impl std::fmt::Display, password: Option<impl std::fmt::Display>) -> Self {
let auth = match password {
Some(password) => format!("{}:{}", username, password),
None => format!("{}:", username),
};
self.header(
http::header::AUTHORIZATION,
format!("Basic {}", openssl::base64::encode_block(auth.as_bytes())),
)
}
pub fn bearer_auth(self, token: impl Into<String>) -> Self {
self.header(http::header::AUTHORIZATION, format!("Bearer {}", token.into()))
}
pub fn body<B1: Body>(self, body: B1) -> RequestBuilder<B1> {
RequestBuilder {
url: self.url,
method: self.method,
body,
base_settings: self.base_settings,
}
}
pub fn text<B1: AsRef<str>>(mut self, body: B1) -> RequestBuilder<body::Text<B1>> {
self.base_settings
.headers
.entry(http::header::CONTENT_TYPE)
.or_insert(HeaderValue::from_static("text/plain; charset=utf-8"));
self.body(body::Text(body))
}
pub fn bytes<B1: AsRef<[u8]>>(mut self, body: B1) -> RequestBuilder<body::Bytes<B1>> {
self.base_settings
.headers
.entry(http::header::CONTENT_TYPE)
.or_insert(HeaderValue::from_static("application/octet-stream"));
self.body(body::Bytes(body))
}
pub fn file(mut self, body: fs::File) -> RequestBuilder<body::File> {
self.base_settings
.headers
.entry(http::header::CONTENT_TYPE)
.or_insert(HeaderValue::from_static("application/octet-stream"));
self.body(body::File(body))
}
#[cfg(feature = "json")]
pub fn json<T: serde::Serialize>(mut self, value: &T) -> Result<RequestBuilder<body::Bytes<Vec<u8>>>> {
let body = serde_json::to_vec(value)?;
self.base_settings
.headers
.entry(http::header::CONTENT_TYPE)
.or_insert(HeaderValue::from_static("application/json; charset=utf-8"));
Ok(self.body(body::Bytes(body)))
}
#[cfg(feature = "json")]
pub fn json_streaming<T: serde::Serialize>(mut self, value: T) -> RequestBuilder<body::Json<T>> {
self.base_settings
.headers
.entry(http::header::CONTENT_TYPE)
.or_insert(HeaderValue::from_static("application/json; charset=utf-8"));
self.body(body::Json(value))
}
#[cfg(feature = "form")]
pub fn form<T: serde::Serialize>(mut self, value: &T) -> Result<RequestBuilder<body::Bytes<Vec<u8>>>> {
let body = serde_urlencoded::to_string(value)?.into_bytes();
self.base_settings
.headers
.entry(http::header::CONTENT_TYPE)
.or_insert(HeaderValue::from_static("application/x-www-form-urlencoded"));
Ok(self.body(body::Bytes(body)))
}
pub fn header<H, V>(self, header: H, value: V) -> Self
where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<V::Error>,
{
self.try_header(header, value).expect("invalid header value")
}
pub fn header_append<H, V>(self, header: H, value: V) -> Self
where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<V::Error>,
{
self.try_header_append(header, value).expect("invalid header value")
}
pub fn try_header<H, V>(mut self, header: H, value: V) -> Result<Self>
where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<V::Error>,
{
header_insert(&mut self.base_settings.headers, header, value)?;
Ok(self)
}
pub fn try_header_append<H, V>(mut self, header: H, value: V) -> Result<Self>
where
H: IntoHeaderName,
V: TryInto<HeaderValue>,
Error: From<V::Error>,
{
header_append(&mut self.base_settings.headers, header, value)?;
Ok(self)
}
pub fn max_headers(mut self, max_headers: usize) -> Self {
self.base_settings.max_headers = max_headers;
self
}
pub fn max_redirections(mut self, max_redirections: u32) -> Self {
self.base_settings.max_redirections = max_redirections;
self
}
pub fn follow_redirects(mut self, follow_redirects: bool) -> Self {
self.base_settings.follow_redirects = follow_redirects;
self
}
pub fn connect_timeout(mut self, duration: Duration) -> Self {
self.base_settings.connect_timeout = duration;
self
}
pub fn read_timeout(mut self, duration: Duration) -> Self {
self.base_settings.read_timeout = duration;
self
}
pub fn timeout(mut self, duration: Duration) -> Self {
self.base_settings.timeout = Some(duration);
self
}
pub fn proxy_settings(mut self, settings: ProxySettings) -> Self {
self.base_settings.proxy_settings = settings;
self
}
#[cfg(feature = "charsets")]
pub fn default_charset(mut self, default_charset: Option<Charset>) -> Self {
self.base_settings.default_charset = default_charset;
self
}
#[cfg(feature = "compress")]
pub fn allow_compression(mut self, allow_compression: bool) -> Self {
self.base_settings.allow_compression = allow_compression;
self
}
pub fn danger_accept_invalid_certs(mut self, accept_invalid_certs: bool) -> Self {
self.base_settings.accept_invalid_certs = accept_invalid_certs;
self
}
pub fn danger_accept_invalid_hostnames(mut self, accept_invalid_hostnames: bool) -> Self {
self.base_settings.accept_invalid_hostnames = accept_invalid_hostnames;
self
}
pub fn add_root_certificate(mut self, cert: Certificate) -> Self {
self.base_settings.root_certificates.0.push(cert);
self
}
}
impl<B: Body> RequestBuilder<B> {
pub fn prepare(self) -> PreparedRequest<B> {
self.try_prepare().expect("failed to prepare request")
}
pub fn try_prepare(self) -> Result<PreparedRequest<B>> {
let mut prepped = PreparedRequest {
url: self.url,
method: self.method,
body: self.body,
base_settings: self.base_settings,
};
header_insert(&mut prepped.base_settings.headers, CONNECTION, "close")?;
prepped.set_compression()?;
match prepped.body.kind()? {
BodyKind::Empty => (),
BodyKind::KnownLength(len) => {
header_insert(&mut prepped.base_settings.headers, CONTENT_LENGTH, len)?;
}
BodyKind::Chunked => {
header_insert(&mut prepped.base_settings.headers, TRANSFER_ENCODING, "chunked")?;
}
}
if let Some(typ) = prepped.body.content_type()? {
header_insert(&mut prepped.base_settings.headers, CONTENT_TYPE, typ)?;
}
header_insert_if_missing(&mut prepped.base_settings.headers, ACCEPT, "*/*")?;
header_insert_if_missing(&mut prepped.base_settings.headers, USER_AGENT, DEFAULT_USER_AGENT)?;
Ok(prepped)
}
pub fn send(self) -> Result<Response> {
self.try_prepare()?.send()
}
}
impl<B> RequestBuilder<B> {
pub fn inspect(&mut self) -> RequestInspector<'_, B> {
RequestInspector(self)
}
}
#[derive(Debug)]
pub struct RequestInspector<'a, B>(&'a mut RequestBuilder<B>);
impl<B> RequestInspector<'_, B> {
pub fn url(&self) -> &Url {
&self.0.url
}
pub fn method(&self) -> &Method {
&self.0.method
}
pub fn body(&mut self) -> &mut B {
&mut self.0.body
}
pub fn headers(&self) -> &HeaderMap {
&self.0.base_settings.headers
}
}
#[test]
#[cfg(feature = "tls")]
fn test_accept_invalid_certs_disabled_by_default() {
let builder = RequestBuilder::new(Method::GET, "https://localhost:7900");
assert_eq!(builder.base_settings.accept_invalid_certs, false);
assert_eq!(builder.base_settings.accept_invalid_hostnames, false);
let prepped = builder.prepare();
assert_eq!(prepped.base_settings.accept_invalid_certs, false);
assert_eq!(prepped.base_settings.accept_invalid_hostnames, false);
}
#[cfg(test)]
mod tests {
use super::*;
use http::header::HeaderMap;
#[test]
fn test_header_insert_exists() {
let mut headers = HeaderMap::new();
headers.insert(USER_AGENT, HeaderValue::from_static("hello"));
header_insert(&mut headers, USER_AGENT, "world").unwrap();
assert_eq!(headers[USER_AGENT], "world");
}
#[test]
fn test_header_insert_missing() {
let mut headers = HeaderMap::new();
header_insert(&mut headers, USER_AGENT, "world").unwrap();
assert_eq!(headers[USER_AGENT], "world");
}
#[test]
fn test_header_insert_if_missing_exists() {
let mut headers = HeaderMap::new();
headers.insert(USER_AGENT, HeaderValue::from_static("hello"));
header_insert_if_missing(&mut headers, USER_AGENT, "world").unwrap();
assert_eq!(headers[USER_AGENT], "hello");
}
#[test]
fn test_header_insert_if_missing_missing() {
let mut headers = HeaderMap::new();
header_insert_if_missing(&mut headers, USER_AGENT, "world").unwrap();
assert_eq!(headers[USER_AGENT], "world");
}
#[test]
fn test_header_append() {
let mut headers = HeaderMap::new();
header_append(&mut headers, USER_AGENT, "hello").unwrap();
header_append(&mut headers, USER_AGENT, "world").unwrap();
let vals: Vec<_> = headers.get_all(USER_AGENT).into_iter().collect();
assert_eq!(vals.len(), 2);
for val in vals {
assert!(val == "hello" || val == "world");
}
}
#[test]
fn test_request_builder_param() {
let prepped = RequestBuilder::new(Method::GET, "http://localhost:1337/foo")
.param("qux", "baz")
.prepare();
assert_eq!(prepped.url().as_str(), "http://localhost:1337/foo?qux=baz");
}
#[test]
fn test_request_builder_params() {
let prepped = RequestBuilder::new(Method::GET, "http://localhost:1337/foo")
.params(&[("qux", "baz"), ("foo", "bar")])
.prepare();
assert_eq!(prepped.url().as_str(), "http://localhost:1337/foo?qux=baz&foo=bar");
}
#[test]
fn test_request_builder_header_insert() {
let prepped = RequestBuilder::new(Method::GET, "http://localhost:1337/foo")
.header("hello", "world")
.prepare();
assert_eq!(prepped.headers()["hello"], "world");
}
#[test]
fn test_request_builder_header_append() {
let prepped = RequestBuilder::new(Method::GET, "http://localhost:1337/foo")
.header_append("hello", "world")
.header_append("hello", "!!!")
.prepare();
let vals: Vec<_> = prepped.headers().get_all("hello").into_iter().collect();
assert_eq!(vals.len(), 2);
for val in vals {
assert!(val == "world" || val == "!!!");
}
}
#[cfg(feature = "compress")]
fn assert_request_content(
builder: RequestBuilder,
status_line: &str,
mut header_lines: Vec<&str>,
body_lines: &[&str],
) {
let mut buf = Vec::new();
let mut prepped = builder.prepare();
prepped
.write_request(&mut buf, &prepped.url().clone(), None)
.expect("error writing request");
let text = std::str::from_utf8(&buf).expect("cannot decode request as utf-8");
let lines: Vec<_> = text.lines().collect();
let req_status_line = lines[0];
let empty_line_pos = lines
.iter()
.position(|l| l.is_empty())
.expect("no empty line in request");
let mut req_header_lines = lines[1..empty_line_pos].to_vec();
let req_body_lines = &lines[empty_line_pos + 1..];
req_header_lines.sort_unstable();
header_lines.sort_unstable();
assert_eq!(req_status_line, status_line);
assert_eq!(req_header_lines, header_lines);
assert_eq!(req_body_lines, body_lines);
}
#[test]
#[cfg(feature = "compress")]
fn test_request_builder_write_request_no_query() {
assert_request_content(
RequestBuilder::new(Method::GET, "http://localhost:1337/foo"),
"GET /foo HTTP/1.1",
vec![
"connection: close",
"accept-encoding: gzip, deflate",
"accept: */*",
&format!("user-agent: {}", DEFAULT_USER_AGENT),
],
&[],
);
}
#[test]
#[cfg(feature = "compress")]
fn test_request_builder_write_request_with_query() {
assert_request_content(
RequestBuilder::new(Method::GET, "http://localhost:1337/foo").param("hello", "world"),
"GET /foo?hello=world HTTP/1.1",
vec![
"connection: close",
"accept-encoding: gzip, deflate",
"accept: */*",
&format!("user-agent: {}", DEFAULT_USER_AGENT),
],
&[],
);
}
#[test]
fn test_prepare_default_headers() {
let prepped = RequestBuilder::new(Method::GET, "http://localhost:1337/foo/qux/baz").prepare();
assert_eq!(prepped.headers()[ACCEPT], "*/*");
assert_eq!(prepped.headers()[USER_AGENT], DEFAULT_USER_AGENT);
}
#[test]
fn test_prepare_custom_headers() {
let prepped = RequestBuilder::new(Method::GET, "http://localhost:1337/foo/qux/baz")
.header(USER_AGENT, "foobaz")
.header("Accept", "nothing")
.prepare();
assert_eq!(prepped.headers()[ACCEPT], "nothing");
assert_eq!(prepped.headers()[USER_AGENT], "foobaz");
}
}