wclient 0.1.7

wclient is a lightweight HTTP client library written in Rust.
Documentation
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
// Copyright 2021 Juan A. Cáceres (cacexp@gmail.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! # Simple Web Client for Rust
//! `wclient` is a lightweigh HTTP web client inspired on [Python Requests](https://docs.python-requests.org/en/latest/).
//! 
//! It allows to send HTTP requests and receive the responses.
//! 
//! 
//! # Features
//! * HTTP 1.1 [Request](crate::Request) and [Response](crate::Response) over plain TCP/IP and TLS
//! * HTTP [Session](crate::Session) to share configuration and a cookie jar among requests
//! * HTTP 1.1 Single Body
//! * HTTPS (v1.1) with default site certificate verification (only with host CA certificates)
//! * HTTPS custom site certificate validation (local directory or certificate chain) in *.pem format
//! * HTTPS client certificate authentication
//! * HTTP Connection pooling
//! * [AuthManager](crate::auth::AuthManager) trait fo authenticating requests (`Athentication` header)
//! * [HttpBasicAuth](crate::auth::HttpBasicAuth) for `Athentication: Basic`
//!
//! # Future Features
//! * Multipart
//! * HTTP 2.0
//!  
//! # User Guide
//! 
//! You can find some examples at [GitHub project examples](https://github.com/cacexp/wclient/tree/master/examples).
//! 
//! To create a `Request`, it is needed a [RequestBuilder](crate::RequestBuilder). 
//! 
//! The `RequestBuilder` has constructor functions for each HTTP method that requires the target `url` string: [connect](crate::RequestBuilder::connect),
//! [delete](crate::RequestBuilder::delete), [get](crate::RequestBuilder::get), [head](crate::RequestBuilder::head), [options](crate::RequestBuilder::options),
//! [patch](crate::RequestBuilder::patch), [post](crate::RequestBuilder::post) and [put](crate::RequestBuilder::put).
//! 
//! The 'RequestBuilder' allows to add name/value data for:
//! * Headers through the functions [header](crate::RequestBuilder::header) for a single header or [headers](crate::RequestBuilder::headers) for a set of headers.
//! Header names are case-insensitive.
//! * Parameters through the functions [param](crate::RequestBuilder::param) for a single parameter or [params](crate::RequestBuilder::params) for a set of parameters.
//! Parameter names are case-sensitive.
//! * Cookies through the functions [cookie](crate::RequestBuilder::cookie) for a single cookie or [cookies](crate::RequestBuilder::cookies) for a set of cookies.
//! Cookie names are case-sensitive.
//! 
//! Also, the `RequestBuilder` allows to set [HttpConfig](crate::HttpConfig) configurations through the [config](crate::RequestBuilder::config) function.
//! Finally, to create a [Request](crate::Request) object, it has to be used the [build](RequestBuilder::build) member function of `RequestBuilder`.
//! 
//! Next example shows how to construct a `GET` request to the URL `http://web.myservice.com/user?id=12345&name=John`
//! 
//! ```no_run
//! use wclient::RequestBuilder;
//!
//! let request = RequestBuilder::get("http://web.myservice.com/user")
//!     .header("Accept", "application/json")
//!     .param("id", "12345")
//!     .param("name", "John")
//!     .build(); 
//! ```  
//! 
//! The `Request` body can be set as a `Vec<u8>` using the function [body](crate::RequestBuilder::body) or 
//! the function [json](crate::RequestBuilder::json) with a JSON Object value form the crate [json](https://docs.rs/json/0.12.4/json/).
//! 
//! 
//! ```no_run
//! use wclient::RequestBuilder;
//! use json::object;
//! let data = object! {
//!    name: "John",
//!    surname: "Smith"
//! };
//! 
//! let mut request = RequestBuilder::post("http://web.myservice.com/user")
//!     .header("Accept", "application/json")
//!     .param("id", "12345")
//!     .json(&data)
//!     .build();

//! // The Response
//! 
//! let response = request.send().unwrap();
//! // Check status code is 200 Success
//! assert_eq!(response.status_code(), 200);
//! let result_json = response.json();
//! // Check the request had JSON content
//! assert!(result_json.is_ok());
//! let result_data = result_json.unwrap();
//! // Print JSON object
//! println!("{:?}", result_data.as_str() )
//! 
//! ``` 
//! 
//! After, created, the `send` function sends the request message to the target URL and returns a `Result<Response, Error>` value.
//! 
//! ## HTTP Connection configuration
//! 
//! The `RequestBuilder` has a function to set a [HttpConfig](crate::config::HttpConfig). Currently, it can be configured:
//! * The Root CA certificates to authenticate the server with HTTPS, see [HttpsVerify](crate::config::HttpsVerify)
//! * The client certificate to be authenticated against the serve with HTTPS, see [HttpsCert](crate::config::HttpsCert)

//! ### Server authentication
//! 
//! By default, `wclient`uses the system CA certificates directory (for example, `/etc/ssl/certs`). Trusted CA can be also passed as a `.pem` file path or a 
//! directory containing certificate files:
//! 
//! ```no_run
//! 
//! use wclient::RequestBuilder;
//! use wclient::config::{HttpsVerify, HttpConfigBuilder};
//! 
//! let config = HttpConfigBuilder::default()
//!    .verify(HttpsVerify::Path(String::from("./config/server.pem")))
//!    .build();
//! 
//! let request = RequestBuilder::get("https://web.myservice.com/user")
//!     .header("Accept", "application/json")
//!     .config(&config);
//! 
//! ```
//! 
//! ### Client authentication
//! 
//! The client app can be authenticated against the HTTPS using a certificate and the assotiated private key by using the [HttpsCert](crate::config::HttpsCert) enum.
//!
//!  **_NOTE:_**  If the client certificate is self-signed or signed by CA that is not in the system or custom CA certificates list, the client certificate must contain
//! the certificate chain to the root CA. In this case, the fist certificate in the file must be the client certificate.
//! 
//! ```no_run
//! 
//! use wclient::RequestBuilder;
//! use wclient::config::{HttpsCert, HttpConfigBuilder};
//! 
//! let config = HttpConfigBuilder::default()
//!    .cert(HttpsCert::CertKey{cert: String::from("/path/client.crt"), key: String::from("/path/client.key")})
//!    .build();
//! 
//! let request = RequestBuilder::get("https://web.myservice.com/user")
//!     .header("Accept", "application/json")
//!     .config(&config)
//!     .build();
//! 
//! ```
//! 
//! ## HTTP Sessions
//! 
//! The [Session](crate::Session) type allows to store common configurations and share cookies through an internal or custom set cookie jar. The `Session`
//! object also makes connection pooling, reusing the same connection to send different requests (if server allows it).
//! 
//! `Session` values are constructed through the [SessionBuilder](crate::SessionBuilder) builder that allows to set a `HttpConfig` value 
//! and a shared pointer to a shared `CookieJar` trait implementation.
//! 
//! ```no_run
//! 
//! use wclient::SessionBuilder;
//! use wclient::config::{HttpsCert,HttpConfigBuilder};
//! 
//! 
//! let config = HttpConfigBuilder::default()
//!    .cert(HttpsCert::CertKey{cert: String::from("/path/client.crt"), key: String::from("/path/client.key")})
//!    .build();
//!     
//! let session = SessionBuilder::new()
//!    .config(&config)
//!    .build();
//! 
//! ```
//! 
//! Once built, the `Session` value allows to create `RequestBuilder` for each HTTP method that shares the `HttpConfig` and `CookieJar`. 
//! The `RequestBuilder` can override the shared config and cookie jar.
//! 
//! ```no_run
//! use wclient::SessionBuilder;
//! 
//! let mut session = SessionBuilder::new().build();
//! 
//! let mut request = session.get("https://service.com/user")
//!     .header("Accept", "application/json")
//!     .build();
//! 
//! let response = request.send();
//! ```
//! 
//! ## Authorization
//! 
//! [RFC 7235](https://www.rfc-editor.org/rfc/rfc7235.html#section-4.1) defines the `WWW-Authenticate` response header where 
//! a server is requesting the client to authenticate the request. The [AuthManager](crate::auth::AuthManager) trait defines
//! the functions to process these kind of authenticate headers and generate the proper headers(typically an `Authorization` header).
//! 
//! `wclient`provides [HttpBasicAuth](crate::auth::HttpBasicAuth) implementation of `AuthManager` trait for `Basic` authentication 
//! which uses a base64 encoded `user:password` as header:
//! 
//!  `Authorization: Basic YW55IGNhcm5hbCBwbGVhc3U=` 
//! 
//! The `SessionBuilder` and `RequestBuilder` have a method 'auth' to set an `AuthManage`. The `AuthManager` has to be contained
//! in a thread-safe `Arc` ref-counter and inside a `Mutex`:
//! 
//! ```no_run
//!  use wclient::auth::HttpBasicAuth;
//!  use wclient::RequestBuilder;
//!  use std::sync::{Arc, Mutex}; 
//! 
//!  let manager = Arc::new(Mutex::new(HttpBasicAuth::new("wclient", "user,1234")));
//!
//!  let mut request = RequestBuilder::get("http://localhost:8000/users/12/")
//!                    .auth(manager)
//!                    .build();
//!  let response = request.send();
//! 
//! ```
//! 

#![allow(dead_code)]

#[macro_use]
extern crate lazy_static;

pub mod config;

pub mod cookie;

pub mod auth;

mod constants;

mod http;

use crate::auth::AuthManager;
use std::sync::Mutex;
use crate::cookie::MemCookieJar;
use crate::cookie::CookieJar;
use std::sync::Arc;
use crate::cookie::Cookie;
use crate::config::{HttpConfig, HttpConfigBuilder};

use crate::constants::{CONTENT_TYPE, CONTENT_TYPE_JSON};
use crate::http::{parse_url, EndPoint, HttpScheme, ClientConnectionFactory};

use std::str::from_utf8;
use std::io::{Error, ErrorKind};
use std::fmt;

use std::collections::HashMap;
use case_insensitive_hashmap::CaseInsensitiveHashMap;
use json::JsonValue;


/// HTTP Request Method
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum HttpMethod {GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH}

impl fmt::Display for HttpMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}",
                match self {
                    Self::GET => "GET",
                    Self::HEAD => "HEAD",
                    Self::POST => "POST",
                    Self::PUT=> "PUT",
                    Self::DELETE=> "DELETE",
                    Self::CONNECT => "CONNECT",
                    Self::OPTIONS => "OPTIONS",
                    Self::TRACE => "TRACE",
                    Self::PATCH=> "PATCH"
                }
        )
    }
}

/// HTTP request
/// 
/// A request is composed of:
/// * HTTP method (`GET`, `POST`, `PUT`, `DELETE`, ... )
/// * Target URL, for example, `https://myservice.com/users`
/// * (optional) Request headers.
/// * (optional) Request path parameters, for example, `id` in the  URL `https://myservice.com/users?id=1111`.
/// * (optional) Server cookies
/// * (optional) Request body of type `Vec[u8]`
/// 
/// Request headers, parameters and cookies are represented by a pair of `name` and `value` strings.
/// Additionally, a [HttpConfig](crate::config::HttpConfig) struct can be used to configure the HTTP connections stablished to
/// send a `Request` and receive a `Response`.
/// 
/// For more information see [HTTP Request](https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages#http_requests).
/// 


pub struct Request {
    /// HTTP method
    pub method: HttpMethod,    
    /// Target URL
    pub(crate) url: String,
    /// Request endpoint
    pub(crate) endpoint: Option<EndPoint>,
    /// Request path
    pub path: String, 
    /// HTTP version
    pub(crate) config: HttpConfig,
    /// Request headers
    pub(crate) headers: CaseInsensitiveHashMap<String>,
    /// CookieJar to get/save cookies
    pub (crate) jar: Option<Arc<Mutex<dyn CookieJar>>>,
    // Request Cookies
    pub(crate) cookies: HashMap<String, String>,
    /// Request params
    pub(crate) params: HashMap<String, String>,
    /// Request body (not implemented multi-part yet)
    pub(crate) body: Vec<u8>,
    /// Session's connection factory
    factory: Option<Arc<Mutex<ClientConnectionFactory>>>,
    /// Session's Auth Manager
    auth: Option<Arc<Mutex<dyn AuthManager>>>,
    /// On-build error
    init_error: Option<Error>
}


impl Request {
   
    /// Checks if this request has body
    pub fn has_body(&self) -> bool {
        self.body.len() > 0
    }

    pub fn url(&self) -> &str {
        self.url.as_str()
    }

    pub (crate) fn endpoint(&self) -> Result<&EndPoint, Error> {
        if self.endpoint.is_none() {
            return Err(Error::new(ErrorKind::InvalidData, "URL has not got a valid endpoint"));
        }

        Ok(self.endpoint.as_ref().unwrap())
    }

    pub (crate) fn path(&self) ->  &str {
        // if no errors path should be always good
        self.path.as_str()
    }

     /// Sends the request to the target URL.
    /// Returns the Response message or `std::io::Error` if any issue happened.
    pub fn send(&mut self) -> Result<Response, Error> {
        
        if let Some(ref error) = self.init_error {
            return Err(Error::new(error.kind(), error.get_ref().unwrap().to_string()));
        }

        if self.endpoint.is_none(){
            return Err(Error::new(ErrorKind::InvalidData, "Cannot get host from URL"));
        }

        let endpoint = self.endpoint.as_ref().unwrap();

        // Get cookies from cookie jar (if any)
        if let Some(ref cookie_jar) = self.jar {
            let active_cookies = cookie_jar.lock().as_mut().unwrap().active_cookies(endpoint.host.as_str(), &self.path, endpoint.scheme == HttpScheme::HTTPS);

            for cookie in active_cookies {
                            // request cookies have prevalence over cookie jar's ones

                if self.cookies.contains_key(&cookie.0) {
                    continue;
                }

                self.cookies.insert(cookie.0, cookie.1);
            }
        }

        let connection = if let Some(ref factory) = &self.factory {
            factory.lock().unwrap().get_connection(endpoint, &self.config)?
        } else {
            ClientConnectionFactory::client_connection(endpoint, &self.config)?
        };
        
        return connection.lock().unwrap().send(self);
        
    }
}

/// Helper builder for [Request](crate::Request)
/// * The Request builder has a constructor for each HTTP method (`get`, `post`, `put`, ...) and a set of member functions
/// to set the request members. 
/// * A `build` function creates `Request`. 
/// 
/// ```no_run
/// use wclient::RequestBuilder;
/// use json::object;
/// let data = object! {
///    name: "John",
///    surname: "Smith"
/// };
/// 
/// let mut request = RequestBuilder::post("Http://web.myservice.com/user")
///     .header("Accept", "application/json")
///     .param("id", "12345")
///     .json(&data)
///     .build();
/// ``` 
pub struct RequestBuilder {
    /// HTTP method
    method: HttpMethod,
    /// Target url
    url: String,
    /// HTTP version
    config: HttpConfig,
    /// Request headers
    headers: CaseInsensitiveHashMap<String>,
    /// CookieJar to get/store server cookies
    jar: Option<Arc<Mutex<dyn CookieJar>>>,
    // Request Cookies
    cookies: HashMap<String, String>,
    /// Request params
    params: HashMap<String, String>,
    /// Request body (not implemented multi-part yet)
    body: Vec<u8>,
    /// Session's connection factory
    factory: Option<Arc<Mutex<ClientConnectionFactory>>>,
     /// Session's Auth Manager
    auth: Option<Arc<Mutex<dyn AuthManager>>>
}

impl RequestBuilder {
    /// Default constructor
    pub fn new<S>(method: HttpMethod, url: S) -> RequestBuilder 
        where S : Into<String> {
        RequestBuilder {
            method,
            url: url.into(),
            config: HttpConfigBuilder::default().build(),
            headers: CaseInsensitiveHashMap::new(),
            jar: None,
            cookies: HashMap::new(),
            params: HashMap::new(),
            body: Vec::new(),
            factory: None,
            auth: None
        }
    }

    /// Creates a `CONNECT` request builder
    pub fn connect<S>(url: S) -> RequestBuilder 
        where S : Into<String> {
        Self::new(HttpMethod::CONNECT, url)
    }

    /// Creates a `DELETE` request builder
    pub fn delete<S>(url: S) -> RequestBuilder 
    where S : Into<String> {
        Self::new(HttpMethod::DELETE, url)
    }

    /// Creates a `GET` request builder
    pub fn get<S>(url: S) -> RequestBuilder 
    where S : Into<String> {
        Self::new(HttpMethod::GET, url)
    }

    /// Creates a `HEAD` request builder
    pub fn head<S>(url: S) -> RequestBuilder 
    where S : Into<String>  {
        Self::new(HttpMethod::HEAD, url)
    }

    /// Creates a `OPTIONS` request builder
    pub fn options<S>(url: S) -> RequestBuilder 
    where S : Into<String> {
        Self::new(HttpMethod::OPTIONS, url)
    }

    /// Creates a `PATCH` request builder
    pub fn patch<S>(url: S) -> RequestBuilder 
    where S : Into<String> {
        Self::new(HttpMethod::PATCH, url)
    }

    /// Creates a `POST` request builder
    pub fn post<S>(url: S) -> RequestBuilder 
    where S : Into<String> {
        Self::new(HttpMethod::POST, url)
    }

    /// Creates a `PUT` request builder
    pub fn put<S>(url: S) -> RequestBuilder 
    where S : Into<String> {
        Self::new(HttpMethod::PUT, url)
    }
    
    /// Creates a `TRACE` request builder
    pub fn trace<S>(url: S) -> RequestBuilder 
    where S : Into<String> {
        Self::new(HttpMethod::TRACE, url)
    }


    /// Sets the `Request` configuration
    pub fn config( mut self, data: &HttpConfig) -> RequestBuilder {
        self.config = data.clone();
        self
    }

    /// Adds a set of headers. If there is an existing header with the same key,
    /// it is overrriden. 
    ///
    /// **Note**: header names are case-insensitive.
    pub fn headers( mut self, data: HashMap<String, String>) -> RequestBuilder {
        self.headers.extend(data);
        self
    }

    /// Adds a header. If there is an existing header with the same `name',
    /// it is overrriden. 
    ///
    /// **Note**: header names are case-insensitive.
    pub fn header<S>(mut self, name: S, value: S) -> RequestBuilder 
    where S : Into<String> {
        self.headers.insert(name.into(), value.into());
        self
    }

    /// Adds a set of parameters. If there is an existing parameter with the same key,
    /// it is overrriden. 
    ///
    /// **Note**: parameter names are case-sensitive.
    pub fn params( mut self, data: HashMap<String, String>) -> RequestBuilder {
        self.params.extend(data);
        self
    }

    /// Adds a parameter. If there is an existing parameter with the same key,
    /// it is overrriden. 
    ///
    /// **Note**: parameter names are case-sensitive.
    pub fn param<S>(mut self, name: S, value: S) -> RequestBuilder 
    where S : Into<String> {
        self.params.insert(name.into(), value.into());
        self
    }

    /// Adds a set of cookies. If there is an existing cookie with the same key,
    /// it is overrriden. 
    ///
    /// **Note**: cookie names are case-sensitive.
    pub fn cookies( mut self, data: HashMap<String, String>) -> RequestBuilder {
        self.params.extend(data);
        self
    }

    /// Adds a cookie. If there is an existing cookie with the same key,
    /// it is overrriden. 
    ///
    /// **Note**: cookie names are case-sensitive.
    pub fn cookie<S>(mut self, name: S, value: S) -> RequestBuilder 
    where S : Into<String> {
        self.cookies.insert(name.into(), value.into());
        self
    }

    /// Sets a CookieJar to get/save session cookies
    
    pub fn cookie_jar(mut self, jar: Arc<Mutex<dyn CookieJar>>) -> RequestBuilder {
        self.jar = Some(jar);
        self
    }

    /// Sets a request body. The `Request` takes ownership of the `data` buffer.
    pub fn body(mut self, data: Vec<u8>) -> RequestBuilder {
        self.body = data;
        self
    }

    /// Sets a json object as request body. The `data` object is marshaled into a buffer using UTF8 coding.
    pub fn json(mut self, data: &JsonValue) -> RequestBuilder {
        let pretty = data.pretty(4);
        self.body = pretty.into_bytes();
        self.headers.insert(String::from(CONTENT_TYPE), String::from(CONTENT_TYPE_JSON));
        self
    }

    /// Transfers session config and references to the Request
    fn session(mut self, session: &Session) -> RequestBuilder {
        self.config = session.config.clone();
        self.jar = Some(session.jar.clone());
        self.factory = Some(Arc::clone(&session.factory));
        if let Some(ref auth) = session.auth {
            self.auth = Some(Arc::clone(auth));
        }
        self
    }

    /// Sets Connection Factory
    pub(crate) fn factory(mut self, factory: Arc<Mutex<ClientConnectionFactory>>) -> RequestBuilder {
        self.factory = Some(factory);
        self
    }

    /// Sets Connection Authenticator for `401 Not Authorized` responses with `WWW-Authenticate` headers 
    pub fn auth(mut self, mgr: Arc<Mutex<dyn AuthManager>>) -> RequestBuilder {
        self.auth = Some(mgr);
        self
    }

    /// Creates a [Request](crate::Request) struct.
    pub fn build(self) -> Request {

        let mut init_error: Option<Error> = None;
        let mut endpoint_holder: Option<EndPoint> = None;

        let url = parse_url(&self.url);
        
        let path = String::from(
            if url.is_ok() {
                url.as_ref().unwrap().path()
            } else {
                "/"
            }
        );
        
        if url.is_ok() {

            let endpoint = EndPoint::from_url(url.as_ref().unwrap());
            
            if endpoint.is_err() {
                init_error = Some(endpoint.err().unwrap());
            } else {
                endpoint_holder = Some(endpoint.unwrap());
            }
        } else {
            init_error = url.err();
        } 

        Request {
            method: self.method,
            url: self.url,
            endpoint: endpoint_holder,
            path, 
            config: self.config,
            headers: self.headers,
            jar: self.jar,
            cookies: self.cookies,
            params: self.params,
            body: self.body,
            factory: self.factory,
            auth: self.auth,
            init_error
        }
    }
}

/// HTTP session used to share configuration and cookies among different requests and responses
/// 
/// The `Session` is constructed by a [SessionBuilder](crate::SessionBuilder) which accepts an [HttpConfig](crate::SessionBuilder) and 
/// a shared [CookieJar](crate::cookie::CookieJar).
/// 
/// When constructed, a `Session` can generate request builders with shared config and cookie environment. 
/// 
/// See [modules documentation](index.html#http-sessions) for session user manual.
/// 
pub struct Session {
    config: HttpConfig,
    jar: Arc<Mutex<dyn CookieJar>>,
    auth: Option<Arc<Mutex<dyn AuthManager>>>,
    factory: Arc<Mutex<ClientConnectionFactory>>
}

impl Session {
    /// Gets session config
    pub fn config(&self) -> &HttpConfig {
        &self.config
    }
  
   /// Creates a `CONNECT` request builder
   pub fn connect<S>(&self, url: S) -> RequestBuilder 
   where S: Into<String> {
        RequestBuilder::new(HttpMethod::CONNECT, url)
        .session(self)   
    }

    /// Creates a `DELETE` request builder
    pub fn delete<S>(&self, url: S) -> RequestBuilder 
    where S: Into<String>  {
        RequestBuilder::new(HttpMethod::DELETE, url)
        .session(self)

    }

    /// Creates a `GET` request builder
    pub fn get<S>(&self, url: S) -> RequestBuilder 
    where S: Into<String> {
        RequestBuilder::new(HttpMethod::GET, url)
        .session(self)  
    }

    /// Creates a `HEAD` request builder
    pub fn head<S>(&self, url: S) -> RequestBuilder 
    where S: Into<String> {
        RequestBuilder::new(HttpMethod::HEAD, url)
        .session(self)
    }

    /// Creates a `OPTIONS` request builder
    pub fn options<S>(&self, url: S) -> RequestBuilder 
    where S: Into<String> {
        RequestBuilder::new(HttpMethod::OPTIONS, url)
        .session(self)
    }

    /// Creates a `PATCH` request builder
    pub fn patch<S>(&self, url: S) -> RequestBuilder 
    where S: Into<String> {
        RequestBuilder::new(HttpMethod::PATCH, url)
        .session(self)
    }

    /// Creates a `POST` request builder
    pub fn post<S>(&self, url: S) -> RequestBuilder 
    where S: Into<String> {
        RequestBuilder::new(HttpMethod::POST, url)
        .session(self)
    }

    /// Creates a `PUT` request builder
    pub fn put<S>(&self, url: S) -> RequestBuilder 
    where S: Into<String> {
        RequestBuilder::new(HttpMethod::PUT, url)
        .session(self)
    }


    /// Creates a `TRACE` request builder
    pub fn trace<S>(&self, url: S) -> RequestBuilder 
    where S: Into<String> {
        RequestBuilder::new(HttpMethod::TRACE, url)
        .session(self)
    }
}

/// [Session](crate::Session) Builder class.
/// 
/// Usage example:
/// 
/// ```no_run
/// use wclient::SessionBuilder;
/// use wclient::config::HttpConfigBuilder;
/// 
/// let config = HttpConfigBuilder::default()
///     // Set config here
///     .build();
/// 
/// let session = SessionBuilder::new()
///     .config(&config)
///     .build();
/// ```
/// 
pub struct SessionBuilder {
    config: Option<HttpConfig>,
    jar: Option<Arc<Mutex<dyn CookieJar>>>,
    auth: Option<Arc<Mutex<dyn AuthManager>>>
}

impl SessionBuilder {

    /// Constructor
    pub fn new() -> SessionBuilder {
        SessionBuilder {
            config: None,
            jar: None,
            auth: None
        }
    }

    /// Sets the `Request` configuration
    pub fn config( mut self, data: &HttpConfig) -> SessionBuilder {
        self.config = Some(data.clone());
        self
    }

     /// Sets a CookieJar to get/save session cookies, uf not provided defauls is [MemCookieJar](crate::cookie::MemCookieJar) 
     pub fn cookie_jar(mut self, jar: Arc<Mutex<dyn CookieJar>>) -> SessionBuilder {
        self.jar = Some(jar);
        self
    }

    pub fn auth(mut self, auth: Arc<Mutex<dyn AuthManager>>) -> SessionBuilder {
        self.auth = Some(auth);
        self
    }

    /// `Session` Builder
    pub fn build(mut self) -> Session {
        if self.jar.is_none() {
            self.jar = Some(Arc::new(Mutex::new(MemCookieJar::new())));
        }

        if self.config.is_none() {
            self.config = Some(HttpConfigBuilder::default().build());
        }
        Session {
            config: self.config.unwrap(),
            jar: self.jar.unwrap(),
            auth: self.auth,
            factory: Arc::new(Mutex::new(ClientConnectionFactory::new()))

        }
    }
}


/// HTTP Response status code
pub type HttpStatusCode = u16;

/// HTTP 100 CONTINUE status code
pub const HTTP_100_CONTINUE: u16 = 100;
/// HTTP 101 SWITCHING_PROTOCOLS status code
pub const HTTP_101_SWITCHING_PROTOCOLS: u16 = 101;
/// HTTP 200 OK status code
pub const HTTP_200_OK: u16 = 200;
/// HTTP 201 CREATED status code
pub const HTTP_201_CREATED: u16 = 201;
/// HTTP 202 ACCEPTED status code
pub const HTTP_202_ACCEPTED: u16 = 202;
/// HTTP 204 NO CONTENT status code
pub const HTTP_204_NO_CONTENT: u16 = 204;
/// HTTP 205 RESET CONTENT status code
pub const HTTP_205_RESET_CONTENT: u16 = 205;
/// HTTP 400 BAD REQUEST status code
pub const HTTP_400_BAD_REQUEST: u16 = 400;
/// HTTP 401 UNAUTHORIZED status code
pub const HTTP_401_UNAUTHORIZED: u16 = 401;
/// HTTP 402 BAD REQUEST status code
pub const HTTP_402_FORBIDDEN: u16 = 402;
/// HTTP 404 NOT FOUND status code
pub const HTTP_404_NOT_FOUND: u16 = 404;
/// HTTP 405 METHOD NOT ALLOWED status code
pub const HTTP_405_METHOD_NOT_ALLOWED: u16 = 405;
/// HTTP 406 NOT ACCEPTABLE status code
pub const HTTP_406_NOT_ACCEPTABLE: u16 = 406;
/// HTTP 408 REQUEST_TIMEOUT status code
pub const HTTP_408_REQUEST_TIMEOUT: u16 = 408;
/// HTTP 500 INTERNAL_SERVE_ERROR status code
pub const HTTP_500_INTERNAL_SERVE_ERROR: u16 = 500;
/// HTTP 501 NOT IMPLEMENTED status code
pub const HTTP_501_NOT_IMPLEMENTED: u16 = 501;


/// List of `Set-Cookie` headers in a HTTP Response
pub type SetCookies = Vec<Cookie>;

/// HTTP Response
/// An HTTP Response is formed by:
/// * Status code
/// * (optional) Response headers
/// * (optional) Server's cookies (header `Set-Cookie`)
/// * (optional) Response body
/// 
/// For mor information see [HTTP Response](https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages#http_responses)
pub struct Response {
    /// Response status code
    pub(crate) status_code: HttpStatusCode,
    /// Response headers
    pub(crate) headers: HashMap<String, String>,
    /// Response cookies
    pub(crate) cookies: SetCookies,
    /// Authorize headers in HTTP `401 Not Authorized` responses
    pub(crate) auth: Vec<String>,
    /// Proxy authorize headers in HTTP `401 Not Authorized` responses
    pub(crate) proxy_auth: Vec<String>,
    /// Response body
    pub(crate) body: Vec<u8>
}

impl Response {
    /// Response default constructor, only sets the status code.
    /// After constructing the value, as struct members are public, they can be
    /// accessed directly
    pub fn new(status: HttpStatusCode) -> Response {
        Response {
            headers: HashMap::new(),
            cookies: SetCookies::new(),
            status_code: status,
            auth: Vec::new(),
            proxy_auth: Vec::new(),
            body: Vec::new()
        }
    }

    /// Get the Response status code
    pub fn status_code(&self) -> HttpStatusCode {
        self.status_code
    }

    /// Get Response Headers.
    pub fn headers(&self) -> &HashMap<String, String> {
        &self.headers
    }

    /// Get Request Cookies.
    pub fn cookie(&self) -> &SetCookies {
        &self.cookies
    }

    /// Get Request Authorization headers
    pub fn auth(&self) -> Vec<&str> {
        self.auth.iter().map(AsRef::as_ref).collect()
    }

    /// Get Request Proxy Authorization headers
    pub fn proxy_auth(&self) -> Vec<&str> {
        self.proxy_auth.iter().map(AsRef::as_ref).collect()
    }

    /// returns if the Response has body
    pub fn has_body(&self) -> bool {self.body.len() > 0}

    /// Response's body builder.
    pub fn body(& self) -> &Vec<u8> {
        &self.body
    }

    /// Checks if the Response has body and tries to parse as a `json::JsonValue'
    pub fn json(&self) -> Result<JsonValue, Error> {
        if self.body.is_empty() {
            return Err(Error::new(ErrorKind::InvalidData, "Empty body"));
        }

        let str_body = from_utf8(&self.body);

        if str_body.is_err() {
            return Err(Error::new(ErrorKind::InvalidData, str_body.err().unwrap()));
        }

        let result = json::parse(str_body.unwrap());

        return if result.is_ok() {
            Ok(result.unwrap())
        } else {
            Err(Error::new(ErrorKind::InvalidData, result.err().unwrap()))
        }
    }
}

#[cfg(test)]
mod test;