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
#![allow(dead_code)]
use unicase::UniCase;
use case_insensitive_hashmap::CaseInsensitiveHashMap;
use std::str::from_utf8;
use std::io::{ErrorKind, Error};
use json::JsonValue;
use std::fmt;
use std::collections::HashMap;
use std::iter::Iterator;
use wcookie::SetCookie;
use std::ops::{Deref, DerefMut};
pub const CONTENT_TYPE: &str = "Content-Type";
pub const APPLICATION_JSON: &str = "application/json";
pub const ACCEPT: &str = "Accept";
#[derive(Copy, Clone, PartialEq, Eq, 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"
}
)
}
}
#[derive(Clone, PartialEq, Debug)]
enum MessageBody {
None,
Single(Vec<u8>),
MultiPart
}
impl MessageBody {
fn is_none(&self) -> bool {
matches!(*self, Self::None)
}
fn is_single(&self) -> bool {
matches!(*self, Self::Single(_))
}
fn is_multipart(&self) -> bool {
matches!(*self, Self::MultiPart)
}
}
pub struct HeaderMap {
map : CaseInsensitiveHashMap<String>
}
impl HeaderMap {
pub fn new() -> HeaderMap {
HeaderMap {
map: CaseInsensitiveHashMap::new()
}
}
pub fn insert<K,V>(&mut self, key: K, value: V) -> bool
where K: Into<String>,
V: Into<String> {
self.map.insert(key.into(),value.into()).is_some()
}
pub fn contains_key<K>(&self, key: K) -> bool
where
K: Into<String>
{
self.map.contains_key(key.into())
}
pub fn get(&self, key: &str) -> Option<&str> {
self.map.get(key).map(|s| s.as_str())
}
pub fn iter(&self) -> HeaderIter {
HeaderIter {
iter: self.map.iter()
}
}
}
impl From<Vec<(String, String)>> for HeaderMap {
fn from(value: Vec<(String, String)>) -> Self {
let mut owned = value;
let mut result = HeaderMap::new();
loop {
if let Some((k,v)) = owned.pop() {
result.insert(k,v);
} else {
break;
}
}
result
}
}
impl From<&Vec<(&str, &str)>> for HeaderMap {
fn from(value: &Vec<(&str, &str)>) -> Self {
let mut result = HeaderMap::new();
for (k, v) in value.iter() {
result.insert(*k,*v);
}
result
}
}
pub struct HeaderIter<'a> {
iter: std::collections::hash_map::Iter<'a, UniCase<String>, String>
}
impl<'a> Iterator for HeaderIter<'a> {
type Item = (&'a str, &'a str);
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(key, value)| (key.as_str(), value.as_str()) )
}
}
pub struct KeyValueMap {
map : HashMap<String, String>
}
impl KeyValueMap {
pub fn new() -> KeyValueMap {
KeyValueMap {
map: HashMap::new()
}
}
pub fn insert<K,V>(&mut self, key: K, value: V) -> bool
where K: Into<String>,
V: Into<String> {
self.map.insert(key.into(),value.into()).is_some()
}
pub fn get(&self, key: &str) -> Option<&str> {
self.map.get(key).map(|s| s.as_str())
}
pub fn contains_key(&self, key: &str) -> bool {
self.map.contains_key(key)
}
pub fn iter(&self) -> KeyValueIter {
KeyValueIter {
iter: self.map.iter()
}
}
}
pub struct KeyValueIter<'a> {
iter: std::collections::hash_map::Iter<'a, String, String>
}
impl<'a> Iterator for KeyValueIter<'a> {
type Item = (&'a str, &'a str);
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(key, value)| (key.as_str(), value.as_str()) )
}
}
pub struct HttpMessage {
headers: HeaderMap,
body: MessageBody
}
impl HttpMessage {
pub fn new() -> HttpMessage {
HttpMessage {
headers : HeaderMap::new(),
body: MessageBody::None
}
}
pub fn insert_header<K,V>(&mut self, key: K, value: V) -> &mut Self
where K: Into<String>,
V: Into<String> {
self.headers.insert(key, value);
self
}
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
pub fn headers_mut(&mut self) -> &mut HeaderMap {
&mut self.headers
}
pub fn has_single_body(&self) -> bool {
self.body.is_single()
}
pub fn has_multipart_body(&self) -> bool {
self.body.is_multipart()
}
pub fn set_body(&mut self, data: Vec<u8>) -> &mut Self {
self.body = MessageBody::Single(data);
self
}
pub fn body (&self) -> Option<&Vec<u8>> {
if let MessageBody::Single(ref body) = self.body {
Some(body)
} else {
None
}
}
pub fn set_json(&mut self, data: &JsonValue) -> &mut Self {
let pretty = data.pretty(4);
self.headers.insert(CONTENT_TYPE, APPLICATION_JSON);
self.set_body(pretty.into_bytes())
}
pub fn json(&self) -> Result<JsonValue, Error> {
if ! self.body.is_single() {
return Err(Error::new(ErrorKind::InvalidData, "Empty body"));
}
let str_body = from_utf8(self.body().unwrap());
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()))
}
}
}
pub struct Request {
base: HttpMessage,
method: HttpMethod,
url: String,
cookies: KeyValueMap,
params: KeyValueMap
}
impl Request {
pub fn new<S>(method: HttpMethod, url: S) -> Request
where S: Into<String>
{
Request {
base: HttpMessage::new(),
method,
url: url.into(),
cookies: KeyValueMap::new(),
params: KeyValueMap::new()
}
}
pub fn connect<S>(url: S) -> Request
where S: Into::<String>
{
Self::new(HttpMethod::CONNECT, url)
}
pub fn delete<S>(url: S) -> Request
where S: Into::<String>
{
Self::new(HttpMethod::DELETE, url)
}
pub fn get<S>(url: S) -> Request
where S: Into::<String>
{
Self::new(HttpMethod::GET, url)
}
pub fn head<S>(url: S) -> Request
where S: Into::<String>
{
Self::new(HttpMethod::HEAD, url)
}
pub fn options<S>(url: S) -> Request
where S: Into::<String>
{
Self::new(HttpMethod::OPTIONS, url)
}
pub fn patch<S>(url: S) -> Request
where S: Into::<String>
{
Self::new(HttpMethod::PATCH, url)
}
pub fn post<S>(url: S) -> Request
where S: Into::<String>
{
Self::new(HttpMethod::POST, url)
}
pub fn put<S>(url: S) -> Request
where S: Into::<String>
{
Self::new(HttpMethod::PUT, url)
}
pub fn trace<S>(url: S) -> Request
where S: Into::<String>
{
Self::new(HttpMethod::TRACE, url)
}
pub fn method(&self) -> HttpMethod {
self.method
}
pub fn insert_param<K, V>(&mut self, key: K, value: V) -> &mut Self
where K: Into<String>,
V: Into<String>
{
self.params.insert(key, value);
self
}
pub fn params(&self) -> &KeyValueMap {
&self.params
}
pub fn params_mut(&mut self) -> &mut KeyValueMap {
&mut self.params
}
pub fn insert_cookie<K, V>(&mut self, key: K, value: V) -> &mut Self
where K: Into<String>,
V: Into<String>
{
self.cookies.insert(key, value);
self
}
pub fn cookies(&self) -> &KeyValueMap {
&self.cookies
}
pub fn cookies_mut(&mut self) -> &mut KeyValueMap {
&mut self.params
}
pub fn url(&self) -> &str {
self.url.as_str()
}
}
impl Deref for Request {
type Target = HttpMessage;
fn deref(&self) -> &HttpMessage {
&self.base
}
}
impl DerefMut for Request {
fn deref_mut(&mut self) -> &mut HttpMessage {
&mut self.base
}
}
impl fmt::Display for Request {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "{} {}", self.method, &self.url)?;
let headers = self.headers.iter();
for (key,value) in headers {
writeln!(f, "{}={}", key, value)?;
}
Ok(())
}
}
pub type HttpStatusCode = u16;
pub const HTTP_100_CONTINUE: u16 = 100;
pub const HTTP_101_SWITCHING_PROTOCOLS: u16 = 101;
pub const HTTP_200_OK: u16 = 200;
pub const HTTP_201_CREATED: u16 = 201;
pub const HTTP_202_ACCEPTED: u16 = 202;
pub const HTTP_203_NON_AUTHORIZATIVE_INFORMATION: u16 = 203;
pub const HTTP_204_NO_CONTENT: u16 = 204;
pub const HTTP_205_RESET_CONTENT: u16 = 205;
pub const HTTP_300_MULTIPLE_CHOICES: u16 = 300;
pub const HTTP_301_MOVED_PERMANENTLY: u16 = 301;
pub const HTTP_302_FOUND: u16 = 302;
pub const HTTP_303_SEE_OTHER: u16 = 303;
pub const HTTP_305_RESET_CONTENT: u16 = 305;
pub const HTTP_307_TEMPORARY_REDIRECT: u16 = 307;
pub const HTTP_400_BAD_REQUEST: u16 = 400;
pub const HTTP_401_UNAUTHORIZED: u16 = 401;
pub const HTTP_402_FORBIDDEN: u16 = 402;
pub const HTTP_404_NOT_FOUND: u16 = 404;
pub const HTTP_405_METHOD_NOT_ALLOWED: u16 = 405;
pub const HTTP_406_NOT_ACCEPTABLE: u16 = 406;
pub const HTTP_408_REQUEST_TIMEOUT: u16 = 408;
pub const HTTP_409_CONFLICT: u16 = 409;
pub const HTTP_410_GONE: u16 = 410;
pub const HTTP_411_LENGTH_REQURED: u16 = 411;
pub const HTTP_413_PAYLOAD_TOO_LARGE: u16 = 413;
pub const HTTP_414_URI_TOO_LONG: u16 = 414;
pub const HTTP_415_UNSUPORTED_MEDIA_TYPE: u16 = 415;
pub const HTTP_417_EXPECTATION_FAILED: u16 = 417;
pub const HTTP_426_UPGRADE_REQUIRED: u16 = 426;
pub const HTTP_500_INTERNAL_SERVE_ERROR: u16 = 500;
pub const HTTP_501_NOT_IMPLEMENTED: u16 = 501;
pub const HTTP_502_BAD_GATEWAY: u16 = 502;
pub const HTTP_503_SERVICE_UNAVAILABLE: u16 = 503;
pub const HTTP_504_GATEWAY_TIMEOUT: u16 = 504;
pub const HTTP_505_HTTP_VERSION_NOT_SUPPORTED: u16 = 505;
type SetCookies = Vec<SetCookie>;
pub struct Response {
base: HttpMessage,
status_code: HttpStatusCode,
cookies: SetCookies,
auth: Vec<String>,
proxy_auth: Vec<String>
}
impl Response {
pub fn new(status: HttpStatusCode) -> Response {
Response {
base: HttpMessage::new(),
cookies: SetCookies::new(),
status_code: status,
auth: Vec::new(),
proxy_auth: Vec::new()
}
}
pub fn status_code(&self) -> HttpStatusCode {
self.status_code
}
pub fn insert_cookie(&mut self, value: SetCookie) -> &mut Self {
self.cookies.push(value);
self
}
pub fn cookies(&self) -> Vec<&SetCookie> {
self.cookies.iter().collect()
}
pub fn insert_auth_headers<S: Into<String>>(&mut self, auth: S) -> &mut Self {
self.auth.push(auth.into());
self
}
pub fn auth_headers(&self) -> &Vec<String> {
&self.auth
}
pub fn auth_headers_mut(&mut self) -> &mut Vec<String> {
&mut self.auth
}
pub fn insert_proxy_auth_header<S: Into<String>>(&mut self, auth: S) -> &mut Self {
self.proxy_auth.push(auth.into());
self
}
pub fn proxy_auth_headers(&self) -> &Vec<String> {
&self.proxy_auth
}
pub fn proxy_auth_headers_mut(&mut self) -> &mut Vec<String> {
&mut self.proxy_auth
}
}
impl Deref for Response {
type Target = HttpMessage;
fn deref(&self) -> &HttpMessage {
&self.base
}
}
impl DerefMut for Response {
fn deref_mut(&mut self) -> &mut HttpMessage {
&mut self.base
}
}
#[cfg(test)]
mod test_request;
#[cfg(test)]
mod test_response;