      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
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765

    use std::fmt::Write as FmtWrite;
    use std::io::Write;
    use std::time::Duration;
    use std::{fmt, mem};

    use actix::Addr;
    use bytes::{BufMut, Bytes, BytesMut};
    use cookie::{Cookie, CookieJar};
    use futures::Stream;
    use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
    use serde::Serialize;
    use serde_json;
    use serde_urlencoded;
    use url::Url;

    use super::connector::{ClientConnector, Connection};
    use super::pipeline::SendRequest;
    use body::Body;
    use error::Error;
    use header::{ContentEncoding, Header, IntoHeaderValue};
    use http::header::{self, HeaderName, HeaderValue};
    use http::{uri, Error as HttpError, HeaderMap, HttpTryFrom, Method, Uri, Version};
    use httpmessage::HttpMessage;
    use httprequest::HttpRequest;

    /// An HTTP Client Request
    ///
    /// ```rust
    /// # extern crate actix_web;
    /// # extern crate futures;
    /// # extern crate tokio;
    /// # use futures::Future;
    /// # use std::process;
    /// use actix_web::{actix, client};
    ///
    /// fn main() {
    ///     actix::run(
    ///         || client::ClientRequest::get("http://www.rust-lang.org") // <- Create request builder
    ///             .header("User-Agent", "Actix-web")
    ///             .finish().unwrap()
    ///             .send()                                    // <- Send http request
    ///             .map_err(|_| ())
    ///             .and_then(|response| {                     // <- server http response
    ///                 println!("Response: {:?}", response);
    /// #               actix::System::current().stop();
    ///                 Ok(())
    ///             }),
    ///     );
    /// }
    /// ```
    pub struct ClientRequest {
        uri: Uri,
        method: Method,
        version: Version,
        headers: HeaderMap,
        body: Body,
        chunked: bool,
        upgrade: bool,
        timeout: Option<Duration>,
        encoding: ContentEncoding,
        response_decompress: bool,
        buffer_capacity: usize,
        conn: ConnectionType,
    }

    enum ConnectionType {
        Default,
        Connector(Addr<ClientConnector>),
        Connection(Connection),
    }

    impl Default for ClientRequest {
        fn default() -> ClientRequest {
            ClientRequest {
                uri: Uri::default(),
                method: Method::default(),
                version: Version::HTTP_11,
                headers: HeaderMap::with_capacity(16),
                body: Body::Empty,
                chunked: false,
                upgrade: false,
                timeout: None,
                encoding: ContentEncoding::Auto,
                response_decompress: true,
                buffer_capacity: 32_768,
                conn: ConnectionType::Default,
            }
        }
    }

    impl ClientRequest {
        /// Create request builder for `GET` request
        pub fn get<U: AsRef<str>>(uri: U) -> ClientRequestBuilder {
            let mut builder = ClientRequest::build();
            builder.method(Method::GET).uri(uri);
            builder
        }

        /// Create request builder for `HEAD` request
        pub fn head<U: AsRef<str>>(uri: U) -> ClientRequestBuilder {
            let mut builder = ClientRequest::build();
            builder.method(Method::HEAD).uri(uri);
            builder
        }

        /// Create request builder for `POST` request
        pub fn post<U: AsRef<str>>(uri: U) -> ClientRequestBuilder {
            let mut builder = ClientRequest::build();
            builder.method(Method::POST).uri(uri);
            builder
        }

        /// Create request builder for `PUT` request
        pub fn put<U: AsRef<str>>(uri: U) -> ClientRequestBuilder {
            let mut builder = ClientRequest::build();
            builder.method(Method::PUT).uri(uri);
            builder
        }

        /// Create request builder for `DELETE` request
        pub fn delete<U: AsRef<str>>(uri: U) -> ClientRequestBuilder {
            let mut builder = ClientRequest::build();
            builder.method(Method::DELETE).uri(uri);
            builder
        }
    }

    impl ClientRequest {
        /// Create client request builder
        pub fn build() -> ClientRequestBuilder {
            ClientRequestBuilder {
                request: Some(ClientRequest::default()),
                err: None,
                cookies: None,
                default_headers: true,
            }
        }

        /// Create client request builder
        pub fn build_from<T: Into<ClientRequestBuilder>>(source: T) -> ClientRequestBuilder {
            source.into()
        }

        /// Get the request URI
        #[inline]
        pub fn uri(&self) -> &Uri {
            &self.uri
        }

        /// Set client request URI
        #[inline]
        pub fn set_uri(&mut self, uri: Uri) {
            self.uri = uri
        }

        /// Get the request method
        #[inline]
        pub fn method(&self) -> &Method {
            &self.method
        }

        /// Set HTTP `Method` for the request
        #[inline]
        pub fn set_method(&mut self, method: Method) {
            self.method = method
        }

        /// Get HTTP version for the request
        #[inline]
        pub fn version(&self) -> Version {
            self.version
        }

        /// Set http `Version` for the request
        #[inline]
        pub fn set_version(&mut self, version: Version) {
            self.version = version
        }

        /// Get the headers from the request
        #[inline]
        pub fn headers(&self) -> &HeaderMap {
            &self.headers
        }

        /// Get a mutable reference to the headers
        #[inline]
        pub fn headers_mut(&mut self) -> &mut HeaderMap {
            &mut self.headers
        }

        /// is chunked encoding enabled
        #[inline]
        pub fn chunked(&self) -> bool {
            self.chunked
        }

        /// is upgrade request
        #[inline]
        pub fn upgrade(&self) -> bool {
            self.upgrade
        }

        /// Content encoding
        #[inline]
        pub fn content_encoding(&self) -> ContentEncoding {
            self.encoding
        }

        /// Decompress response payload
        #[inline]
        pub fn response_decompress(&self) -> bool {
            self.response_decompress
        }

        /// Requested write buffer capacity
        pub fn write_buffer_capacity(&self) -> usize {
            self.buffer_capacity
        }

        /// Get body of this response
        #[inline]
        pub fn body(&self) -> &Body {
            &self.body
        }

        /// Set a body
        pub fn set_body<B: Into<Body>>(&mut self, body: B) {
            self.body = body.into();
        }

        /// Extract body, replace it with `Empty`
        pub(crate) fn replace_body(&mut self, body: Body) -> Body {
            mem::replace(&mut self.body, body)
        }

        /// Send request
        ///
        /// This method returns a future that resolves to a ClientResponse
        pub fn send(mut self) -> SendRequest {
            let timeout = self.timeout.take();
            let send = match mem::replace(&mut self.conn, ConnectionType::Default) {
                ConnectionType::Default => SendRequest::new(self),
                ConnectionType::Connector(conn) => SendRequest::with_connector(self, conn),
                ConnectionType::Connection(conn) => SendRequest::with_connection(self, conn),
            };
            if let Some(timeout) = timeout {
                send.timeout(timeout)
            } else {
                send
            }
        }
    }

    impl fmt::Debug for ClientRequest {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            let res = writeln!(
                f,
                "\nClientRequest {:?} {}:{}",
                self.version, self.method, self.uri
            );
            let _ = writeln!(f, "  headers:");
            for (key, val) in self.headers.iter() {
                let _ = writeln!(f, "    {:?}: {:?}", key, val);
            }
            res
        }
    }

    /// An HTTP Client request builder
    ///
    /// This type can be used to construct an instance of `ClientRequest` through a
    /// builder-like pattern.
    pub struct ClientRequestBuilder {
        request: Option<ClientRequest>,
        err: Option<HttpError>,
        cookies: Option<CookieJar>,
        default_headers: bool,
    }

    impl ClientRequestBuilder {
        /// Set HTTP URI of request.
        #[inline]
        pub fn uri<U: AsRef<str>>(&mut self, uri: U) -> &mut Self {
            match Url::parse(uri.as_ref()) {
                Ok(url) => self._uri(url.as_str()),
                Err(_) => self._uri(uri.as_ref()),
            }
        }

        fn _uri(&mut self, url: &str) -> &mut Self {
            match Uri::try_from(url) {
                Ok(uri) => {
                    // set request host header
                    if let Some(host) = uri.host() {
                        self.set_header(header::HOST, host);
                    }
                    if let Some(parts) = parts(&mut self.request, &self.err) {
                        parts.uri = uri;
                    }
                }
                Err(e) => self.err = Some(e.into()),
            }
            self
        }

        /// Set HTTP method of this request.
        #[inline]
        pub fn method(&mut self, method: Method) -> &mut Self {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                parts.method = method;
            }
            self
        }

        /// Set HTTP method of this request.
        #[inline]
        pub fn get_method(&mut self) -> &Method {
            let parts =
                parts(&mut self.request, &self.err).expect("cannot reuse request builder");
            &parts.method
        }

        /// Set HTTP version of this request.
        ///
        /// By default requests's HTTP version depends on network stream
        #[inline]
        pub fn version(&mut self, version: Version) -> &mut Self {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                parts.version = version;
            }
            self
        }

        /// Set a header.
        ///
        /// ```rust
        /// # extern crate mime;
        /// # extern crate actix_web;
        /// # use actix_web::client::*;
        /// #
        /// use actix_web::{client, http};
        ///
        /// fn main() {
        ///     let req = client::ClientRequest::build()
        ///         .set(http::header::Date::now())
        ///         .set(http::header::ContentType(mime::TEXT_HTML))
        ///         .finish()
        ///         .unwrap();
        /// }
        /// ```
        #[doc(hidden)]
        pub fn set<H: Header>(&mut self, hdr: H) -> &mut Self {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                match hdr.try_into() {
                    Ok(value) => {
                        parts.headers.insert(H::name(), value);
                    }
                    Err(e) => self.err = Some(e.into()),
                }
            }
            self
        }

        /// Append a header.
        ///
        /// Header gets appended to existing header.
        /// To override header use `set_header()` method.
        ///
        /// ```rust
        /// # extern crate http;
        /// # extern crate actix_web;
        /// # use actix_web::client::*;
        /// #
        /// use http::header;
        ///
        /// fn main() {
        ///     let req = ClientRequest::build()
        ///         .header("X-TEST", "value")
        ///         .header(header::CONTENT_TYPE, "application/json")
        ///         .finish()
        ///         .unwrap();
        /// }
        /// ```
        pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self
        where
            HeaderName: HttpTryFrom<K>,
            V: IntoHeaderValue,
        {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                match HeaderName::try_from(key) {
                    Ok(key) => match value.try_into() {
                        Ok(value) => {
                            parts.headers.append(key, value);
                        }
                        Err(e) => self.err = Some(e.into()),
                    },
                    Err(e) => self.err = Some(e.into()),
                };
            }
            self
        }

        /// Set a header.
        pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
        where
            HeaderName: HttpTryFrom<K>,
            V: IntoHeaderValue,
        {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                match HeaderName::try_from(key) {
                    Ok(key) => match value.try_into() {
                        Ok(value) => {
                            parts.headers.insert(key, value);
                        }
                        Err(e) => self.err = Some(e.into()),
                    },
                    Err(e) => self.err = Some(e.into()),
                };
            }
            self
        }

        /// Set a header only if it is not yet set.
        pub fn set_header_if_none<K, V>(&mut self, key: K, value: V) -> &mut Self
        where
            HeaderName: HttpTryFrom<K>,
            V: IntoHeaderValue,
        {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                match HeaderName::try_from(key) {
                    Ok(key) => if !parts.headers.contains_key(&key) {
                        match value.try_into() {
                            Ok(value) => {
                                parts.headers.insert(key, value);
                            }
                            Err(e) => self.err = Some(e.into()),
                        }
                    },
                    Err(e) => self.err = Some(e.into()),
                };
            }
            self
        }

        /// Set content encoding.
        ///
        /// By default `ContentEncoding::Identity` is used.
        #[inline]
        pub fn content_encoding(&mut self, enc: ContentEncoding) -> &mut Self {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                parts.encoding = enc;
            }
            self
        }

        /// Enables automatic chunked transfer encoding
        #[inline]
        pub fn chunked(&mut self) -> &mut Self {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                parts.chunked = true;
            }
            self
        }

        /// Enable connection upgrade
        #[inline]
        pub fn upgrade(&mut self) -> &mut Self {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                parts.upgrade = true;
            }
            self
        }

        /// Set request's content type
        #[inline]
        pub fn content_type<V>(&mut self, value: V) -> &mut Self
        where
            HeaderValue: HttpTryFrom<V>,
        {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                match HeaderValue::try_from(value) {
                    Ok(value) => {
                        parts.headers.insert(header::CONTENT_TYPE, value);
                    }
                    Err(e) => self.err = Some(e.into()),
                };
            }
            self
        }

        /// Set content length
        #[inline]
        pub fn content_length(&mut self, len: u64) -> &mut Self {
            let mut wrt = BytesMut::new().writer();
            let _ = write!(wrt, "{}", len);
            self.header(header::CONTENT_LENGTH, wrt.get_mut().take().freeze())
        }

        /// Set a cookie
        ///
        /// ```rust
        /// # extern crate actix_web;
        /// use actix_web::{client, http};
        ///
        /// fn main() {
        ///     let req = client::ClientRequest::build()
        ///         .cookie(
        ///             http::Cookie::build("name", "value")
        ///                 .domain("www.rust-lang.org")
        ///                 .path("/")
        ///                 .secure(true)
        ///                 .http_only(true)
        ///                 .finish(),
        ///         )
        ///         .finish()
        ///         .unwrap();
        /// }
        /// ```
        pub fn cookie<'c>(&mut self, cookie: Cookie<'c>) -> &mut Self {
            if self.cookies.is_none() {
                let mut jar = CookieJar::new();
                jar.add(cookie.into_owned());
                self.cookies = Some(jar)
            } else {
                self.cookies.as_mut().unwrap().add(cookie.into_owned());
            }
            self
        }

        /// Do not add default request headers.
        /// By default `Accept-Encoding` and `User-Agent` headers are set.
        pub fn no_default_headers(&mut self) -> &mut Self {
            self.default_headers = false;
            self
        }

        /// Disable automatic decompress response body
        pub fn disable_decompress(&mut self) -> &mut Self {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                parts.response_decompress = false;
            }
            self
        }

        /// Set write buffer capacity
        ///
        /// Default buffer capacity is 32kb
        pub fn write_buffer_capacity(&mut self, cap: usize) -> &mut Self {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                parts.buffer_capacity = cap;
            }
            self
        }

        /// Set request timeout
        ///
        /// Request timeout is a total time before response should be received.
        /// Default value is 5 seconds.
        pub fn timeout(&mut self, timeout: Duration) -> &mut Self {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                parts.timeout = Some(timeout);
            }
            self
        }

        /// Send request using custom connector
        pub fn with_connector(&mut self, conn: Addr<ClientConnector>) -> &mut Self {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                parts.conn = ConnectionType::Connector(conn);
            }
            self
        }

        /// Send request using existing `Connection`
        pub fn with_connection(&mut self, conn: Connection) -> &mut Self {
            if let Some(parts) = parts(&mut self.request, &self.err) {
                parts.conn = ConnectionType::Connection(conn);
            }
            self
        }

        /// This method calls provided closure with builder reference if
        /// value is `true`.
        pub fn if_true<F>(&mut self, value: bool, f: F) -> &mut Self
        where
            F: FnOnce(&mut ClientRequestBuilder),
        {
            if value {
                f(self);
            }
            self
        }

        /// This method calls provided closure with builder reference if
        /// value is `Some`.
        pub fn if_some<T, F>(&mut self, value: Option<T>, f: F) -> &mut Self
        where
            F: FnOnce(T, &mut ClientRequestBuilder),
        {
            if let Some(val) = value {
                f(val, self);
            }
            self
        }

        /// Set a body and generate `ClientRequest`.
        ///
        /// `ClientRequestBuilder` can not be used after this call.
        pub fn body<B: Into<Body>>(&mut self, body: B) -> Result<ClientRequest, Error> {
            if let Some(e) = self.err.take() {
                return Err(e.into());
            }

            if self.default_headers {
                // enable br only for https
                let https = if let Some(parts) = parts(&mut self.request, &self.err) {
                    parts
                        .uri
                        .scheme_part()
                        .map(|s| s == &uri::Scheme::HTTPS)
                        .unwrap_or(true)
                } else {
                    true
                };

                if https {
                    self.set_header_if_none(header::ACCEPT_ENCODING, "br, gzip, deflate");
                } else {
                    self.set_header_if_none(header::ACCEPT_ENCODING, "gzip, deflate");
                }

                self.set_header_if_none(
                    header::USER_AGENT,
                    concat!("Actix-web/", env!("CARGO_PKG_VERSION")),
                );
            }

            let mut request = self.request.take().expect("cannot reuse request builder");

            // set cookies
            if let Some(ref mut jar) = self.cookies {
                let mut cookie = String::new();
                for c in jar.delta() {
                    let name = percent_encode(c.name().as_bytes(), USERINFO_ENCODE_SET);
                    let value = percent_encode(c.value().as_bytes(), USERINFO_ENCODE_SET);
                    let _ = write!(&mut cookie, "; {}={}", name, value);
                }
                request.headers.insert(
                    header::COOKIE,
                    HeaderValue::from_str(&cookie.as_str()[2..]).unwrap(),
                );
            }
            request.body = body.into();
            Ok(request)
        }

        /// Set a JSON body and generate `ClientRequest`
        ///
        /// `ClientRequestBuilder` can not be used after this call.
        pub fn json<T: Serialize>(&mut self, value: T) -> Result<ClientRequest, Error> {
            let body = serde_json::to_string(&value)?;

            let contains = if let Some(parts) = parts(&mut self.request, &self.err) {
                parts.headers.contains_key(header::CONTENT_TYPE)
            } else {
                true
            };
            if !contains {
                self.header(header::CONTENT_TYPE, "application/json");
            }

            self.body(body)
        }

        /// Set a urlencoded body and generate `ClientRequest`
        ///
        /// `ClientRequestBuilder` can not be used after this call.
        pub fn form<T: Serialize>(&mut self, value: T) -> Result<ClientRequest, Error> {
            let body = serde_urlencoded::to_string(&value)?;

            let contains = if let Some(parts) = parts(&mut self.request, &self.err) {
                parts.headers.contains_key(header::CONTENT_TYPE)
            } else {
                true
            };
            if !contains {
                self.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
            }

            self.body(body)
        }

        /// Set a streaming body and generate `ClientRequest`.
        ///
        /// `ClientRequestBuilder` can not be used after this call.
        pub fn streaming<S, E>(&mut self, stream: S) -> Result<ClientRequest, Error>
        where
            S: Stream<Item = Bytes, Error = E> + 'static,
            E: Into<Error>,
        {
            self.body(Body::Streaming(Box::new(stream.map_err(|e| e.into()))))
        }

        /// Set an empty body and generate `ClientRequest`
        ///
        /// `ClientRequestBuilder` can not be used after this call.
        pub fn finish(&mut self) -> Result<ClientRequest, Error> {
            self.body(Body::Empty)
        }

        /// This method construct new `ClientRequestBuilder`
        pub fn take(&mut self) -> ClientRequestBuilder {
            ClientRequestBuilder {
                request: self.request.take(),
                err: self.err.take(),
                cookies: self.cookies.take(),
                default_headers: self.default_headers,
            }
        }
    }

    #[inline]
    fn parts<'a>(
        parts: &'a mut Option<ClientRequest>, err: &Option<HttpError>,
    ) -> Option<&'a mut ClientRequest> {
        if err.is_some() {
            return None;
        }
        parts.as_mut()
    }

    impl fmt::Debug for ClientRequestBuilder {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            if let Some(ref parts) = self.request {
                let res = writeln!(
                    f,
                    "\nClientRequestBuilder {:?} {}:{}",
                    parts.version, parts.method, parts.uri
                );
                let _ = writeln!(f, "  headers:");
                for (key, val) in parts.headers.iter() {
                    let _ = writeln!(f, "    {:?}: {:?}", key, val);
                }
                res
            } else {
                write!(f, "ClientRequestBuilder(Consumed)")
            }
        }
    }

    /// Create `ClientRequestBuilder` from `HttpRequest`
    ///
    /// It is useful for proxy requests. This implementation
    /// copies all request headers and the method.
    impl<'a, S: 'static> From<&'a HttpRequest<S>> for ClientRequestBuilder {
        fn from(req: &'a HttpRequest<S>) -> ClientRequestBuilder {
            let mut builder = ClientRequest::build();
            for (key, value) in req.headers() {
                builder.header(key.clone(), value.clone());
            }
            builder.method(req.method().clone());
            builder
        }
    }

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g. `str,u8` or `String,struct:Vec,test`)