ic_http_certification/http/
http_request.rs

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
use crate::{HeaderField, HttpCertificationError, HttpCertificationResult};
use candid::{
    types::{Serializer, Type, TypeInner},
    CandidType, Deserialize,
};
pub use http::Method;
use http::Uri;
use serde::Deserializer;
use std::{borrow::Cow, str::FromStr};

#[derive(Debug, Clone, PartialEq, Eq)]
struct MethodWrapper(Method);

impl CandidType for MethodWrapper {
    fn _ty() -> Type {
        TypeInner::Text.into()
    }

    fn idl_serialize<S>(&self, serializer: S) -> Result<(), S::Error>
    where
        S: Serializer,
    {
        self.0.as_str().idl_serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for MethodWrapper {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        String::deserialize(deserializer).and_then(|method| {
            Method::from_str(&method)
                .map(Into::into)
                .map_err(|_| serde::de::Error::custom("Invalid HTTP method"))
        })
    }
}

impl From<Method> for MethodWrapper {
    fn from(method: Method) -> Self {
        Self(method)
    }
}

/// A Candid-encodable representation of an HTTP request. This struct is used by
/// the `http_request` method of the HTTP Gateway Protocol's Candid interface.
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpRequest, Method};
///
/// let request = HttpRequest::builder()
///     .with_method(Method::GET)
///     .with_url("/")
///     .with_headers(vec![("X-Custom-Foo".into(), "Bar".into())])
///     .with_body(&[1, 2, 3])
///     .with_certificate_version(2)
///     .build();
///
/// assert_eq!(request.method(), Method::GET);
/// assert_eq!(request.url(), "/");
/// assert_eq!(request.headers(), &[("X-Custom-Foo".into(), "Bar".into())]);
/// assert_eq!(request.body(), &[1, 2, 3]);
/// assert_eq!(request.certificate_version(), Some(2));
/// ```
///
/// # Helpers
///
/// There are also a number of convenience methods for quickly creating an [HttpRequest] with
/// commonly used HTTP methods:
///
/// - [GET](HttpRequest::get)
/// - [POST](HttpRequest::post)
/// - [PUT](HttpRequest::put)
/// - [PATCH](HttpRequest::patch)
/// - [DELETE](HttpRequest::delete)
///
/// ```
/// use ic_http_certification::HttpRequest;
///
/// let request = HttpRequest::get("/").build();
///
/// assert_eq!(request.method(), "GET");
/// assert_eq!(request.url(), "/");
/// ```
#[derive(Clone, Debug, CandidType, Deserialize, PartialEq, Eq)]
pub struct HttpRequest<'a> {
    /// HTTP request method.
    method: MethodWrapper,

    /// HTTP request URL.
    url: String,

    /// HTTP request headers.
    headers: Vec<HeaderField>,

    /// HTTP request body as an array of bytes.
    body: Cow<'a, [u8]>,

    /// The max response verification version to use in the response's
    /// certificate.
    certificate_version: Option<u16>,
}

impl<'a> HttpRequest<'a> {
    /// Creates a new [HttpRequestBuilder] initialized with a GET method and
    /// the given URL.
    ///
    /// This method returns an instance of [HttpRequestBuilder] which can be
    /// used to create an [HttpRequest].
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::{HttpRequest, Method};
    ///
    /// let request = HttpRequest::get("/").build();
    ///
    /// assert_eq!(request.method(), Method::GET);
    /// ```
    pub fn get(url: impl Into<String>) -> HttpRequestBuilder<'a> {
        HttpRequestBuilder::new()
            .with_method(Method::GET)
            .with_url(url)
    }

    /// Creates a new [HttpRequestBuilder] initialized with a POST method and
    /// the given URL.
    ///
    /// This method returns an instance of [HttpRequestBuilder] which can be
    /// used to create an [HttpRequest].
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::{HttpRequest, Method};
    ///
    /// let request = HttpRequest::post("/").build();
    ///
    /// assert_eq!(request.method(), Method::POST);
    /// ```
    pub fn post(url: impl Into<String>) -> HttpRequestBuilder<'a> {
        HttpRequestBuilder::new()
            .with_method(Method::POST)
            .with_url(url)
    }

    /// Creates a new [HttpRequestBuilder] initialized with a PUT method and
    /// the given URL.
    ///
    /// This method returns an instance of [HttpRequestBuilder] which can be
    /// used to create an [HttpRequest].
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::{HttpRequest, Method};
    ///
    /// let request = HttpRequest::put("/").build();
    ///
    /// assert_eq!(request.method(), Method::PUT);
    /// ```
    pub fn put(url: impl Into<String>) -> HttpRequestBuilder<'a> {
        HttpRequestBuilder::new()
            .with_method(Method::PUT)
            .with_url(url)
    }

    /// Creates a new [HttpRequestBuilder] initialized with a PATCH method and
    /// the given URL.
    ///
    /// This method returns an instance of [HttpRequestBuilder] which can be
    /// used to create an [HttpRequest].
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::{HttpRequest, Method};
    ///
    /// let request = HttpRequest::patch("/").build();
    ///
    /// assert_eq!(request.method(), Method::PATCH);
    /// ```
    pub fn patch(url: impl Into<String>) -> HttpRequestBuilder<'a> {
        HttpRequestBuilder::new()
            .with_method(Method::PATCH)
            .with_url(url)
    }

    /// Creates a new [HttpRequestBuilder] initialized with a DELETE method and
    /// the given URL.
    ///
    /// This method returns an instance of [HttpRequestBuilder] which can be
    /// used to create an [HttpRequest].
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::{HttpRequest, Method};
    ///
    /// let request = HttpRequest::delete("/").build();
    ///
    /// assert_eq!(request.method(), Method::DELETE);
    /// ```
    pub fn delete(url: impl Into<String>) -> HttpRequestBuilder<'a> {
        HttpRequestBuilder::new()
            .with_method(Method::DELETE)
            .with_url(url)
    }

    /// Creates and returns an instance of [HttpRequestBuilder], a builder-style object
    /// which can be used to create an [HttpRequest].
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::{HttpRequest, Method};
    ///
    /// let request = HttpRequest::builder()
    ///     .with_method(Method::GET)
    ///     .with_url("/")
    ///     .with_headers(vec![("X-Custom-Foo".into(), "Bar".into())])
    ///     .with_body(&[1, 2, 3])
    ///     .with_certificate_version(2)
    ///     .build();
    ///
    /// assert_eq!(request.method(), Method::GET);
    /// assert_eq!(request.url(), "/");
    /// assert_eq!(request.headers(), &[("X-Custom-Foo".into(), "Bar".into())]);
    /// assert_eq!(request.body(), &[1, 2, 3]);
    /// assert_eq!(request.certificate_version(), Some(2));
    /// ```
    #[inline]
    pub fn builder() -> HttpRequestBuilder<'a> {
        HttpRequestBuilder::new()
    }

    /// Returns the HTTP method of the request.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("/").build();
    ///
    /// assert_eq!(request.method(), "GET");
    /// ```
    #[inline]
    pub fn method(&self) -> &Method {
        &self.method.0
    }

    /// Returns the URL of the request.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("/").build();
    ///
    /// assert_eq!(request.url(), "/");
    /// ```
    #[inline]
    pub fn url(&self) -> &str {
        &self.url
    }

    /// Returns the headers of the request.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("/")
    ///     .with_headers(vec![("Accept".into(), "text/plain".into())])
    ///     .build();
    ///
    /// assert_eq!(request.headers(), &[("Accept".into(), "text/plain".into())]);
    /// ```
    #[inline]
    pub fn headers(&self) -> &[HeaderField] {
        &self.headers
    }

    /// Returns the body of the request.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("/")
    ///     .with_body(&[1, 2, 3])
    ///     .build();
    ///
    /// assert_eq!(request.body(), &[1, 2, 3]);
    /// ```
    #[inline]
    pub fn body(&self) -> &[u8] {
        &self.body
    }

    /// Returns the max response verification version to use in the response's
    /// certificate.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("/")
    ///     .with_certificate_version(2)
    ///     .build();
    ///
    /// assert_eq!(request.certificate_version(), Some(2));
    /// ```
    #[inline]
    pub fn certificate_version(&self) -> Option<u16> {
        self.certificate_version
    }

    /// Returns the path of the request URL, without domain, query parameters or fragments.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("https://canister.com/sample-asset.txt").build();
    ///
    /// assert_eq!(request.get_path().unwrap(), "/sample-asset.txt");
    /// ```
    pub fn get_path(&self) -> HttpCertificationResult<String> {
        let uri = self
            .url
            .parse::<Uri>()
            .map_err(|_| HttpCertificationError::MalformedUrl(self.url.to_string()))?;

        let decoded_path = urlencoding::decode(uri.path()).map(|path| path.into_owned())?;
        Ok(decoded_path)
    }

    /// Returns the query parameters of the request URL, if any, as a string.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("https://canister.com/sample-asset.txt?foo=bar").build();
    ///
    /// assert_eq!(request.get_query().unwrap(), Some("foo=bar".to_string()));
    /// ```
    pub fn get_query(&self) -> HttpCertificationResult<Option<String>> {
        self.url
            .parse::<Uri>()
            .map(|uri| uri.query().map(|uri| uri.to_owned()))
            .map_err(|_| HttpCertificationError::MalformedUrl(self.url.to_string()))
    }
}

/// An HTTP request builder.
///
/// This type can be used to construct an instance of an [HttpRequest] using a builder-like
/// pattern.
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpRequestBuilder, Method};
///
/// let request = HttpRequestBuilder::new()
///     .with_method(Method::GET)
///     .with_url("/")
///     .with_headers(vec![("X-Custom-Foo".into(), "Bar".into())])
///     .with_body(&[1, 2, 3])
///     .with_certificate_version(2)
///     .build();
///
/// assert_eq!(request.method(), Method::GET);
/// assert_eq!(request.url(), "/");
/// assert_eq!(request.headers(), &[("X-Custom-Foo".into(), "Bar".into())]);
/// assert_eq!(request.body(), &[1, 2, 3]);
/// assert_eq!(request.certificate_version(), Some(2));
/// ```
#[derive(Debug, Clone, Default)]
pub struct HttpRequestBuilder<'a> {
    method: Option<MethodWrapper>,
    url: Option<String>,
    headers: Vec<HeaderField>,
    body: Cow<'a, [u8]>,
    certificate_version: Option<u16>,
}

impl<'a> HttpRequestBuilder<'a> {
    /// Creates a new instance of the [HttpRequestBuilder] that can be used to
    /// construct an [HttpRequest].
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::{HttpRequestBuilder, Method};
    ///
    /// let request = HttpRequestBuilder::new()
    ///     .with_method(Method::GET)
    ///     .with_url("/")
    ///     .with_headers(vec![("X-Custom-Foo".into(), "Bar".into())])
    ///     .with_body(&[1, 2, 3])
    ///     .with_certificate_version(2)
    ///     .build();
    ///
    /// assert_eq!(request.method(), Method::GET);
    /// assert_eq!(request.url(), "/");
    /// assert_eq!(request.headers(), &[("X-Custom-Foo".into(), "Bar".into())]);
    /// assert_eq!(request.body(), &[1, 2, 3]);
    /// assert_eq!(request.certificate_version(), Some(2));
    /// ```
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the HTTP method of the [HttpRequest].
    ///
    /// This function will accept both owned and borrowed values. By default,
    /// the method will be set to `"GET"`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::{HttpRequestBuilder, Method};
    ///
    /// let request = HttpRequestBuilder::new()
    ///     .with_method(Method::GET)
    ///     .build();
    ///
    /// assert_eq!(request.method(), Method::GET);
    /// ```
    #[inline]
    pub fn with_method(mut self, method: Method) -> Self {
        self.method = Some(method.into());

        self
    }

    /// Set the HTTP URL of the [HttpRequest].
    ///
    /// This function will accept both owned and borrowed values. By default,
    /// the URL will be set to `"/"`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequestBuilder;
    ///
    /// let request = HttpRequestBuilder::new()
    ///     .with_url("/")
    ///     .build();
    ///
    /// assert_eq!(request.url(), "/");
    /// ```
    #[inline]
    pub fn with_url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());

        self
    }

    /// Set the HTTP headers of the [HttpRequest].
    ///
    /// By default the headers will be an empty array.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::{HttpRequestBuilder, HeaderField};
    ///
    /// let request = HttpRequestBuilder::new()
    ///     .with_headers(vec![("X-Custom-Foo".into(), "Bar".into())])
    ///     .build();
    ///
    /// assert_eq!(request.headers(), &[("X-Custom-Foo".into(), "Bar".into())]);
    /// ```
    #[inline]
    pub fn with_headers(mut self, headers: Vec<HeaderField>) -> Self {
        self.headers = headers;

        self
    }

    /// Set the HTTP body of the [HttpRequest].
    ///
    /// This function will accept both owned and borrowed values. By default,
    /// the body will be an empty array.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequestBuilder;
    ///
    /// let request = HttpRequestBuilder::new()
    ///     .with_body(&[1, 2, 3])
    ///     .build();
    ///
    /// assert_eq!(request.body(), &[1, 2, 3]);
    /// ```
    #[inline]
    pub fn with_body(mut self, body: impl Into<Cow<'a, [u8]>>) -> Self {
        self.body = body.into();

        self
    }

    /// Set the max response verification vwersion to use in the
    /// [crate::HttpResponse] certificate.
    ///
    /// By default, the certificate version will be `None`, which
    /// is equivalent to setting it to version `1`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequestBuilder;
    ///
    /// let request = HttpRequestBuilder::new()
    ///     .with_certificate_version(2)
    ///     .build();
    ///
    /// assert_eq!(request.certificate_version(), Some(2));
    /// ```
    #[inline]
    pub fn with_certificate_version(mut self, certificate_version: u16) -> Self {
        self.certificate_version = Some(certificate_version);

        self
    }

    /// Build an [HttpRequest] from the builder.
    ///
    /// If the method is not set, it will default to `"GET"`.
    /// If the URL is not set, it will default to `"/"`.
    /// If the certificate version is not set, it will default to `1`.
    /// If the headers or body are not set, they will default to empty arrays.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::{HttpRequestBuilder, Method};
    ///
    /// let request = HttpRequestBuilder::new()
    ///     .with_method(Method::GET)
    ///     .with_url("/")
    ///     .with_headers(vec![("X-Custom-Foo".into(), "Bar".into())])
    ///     .with_body(&[1, 2, 3])
    ///     .with_certificate_version(2)
    ///     .build();
    ///
    /// assert_eq!(request.method(), Method::GET);
    /// assert_eq!(request.url(), "/");
    /// assert_eq!(request.headers(), &[("X-Custom-Foo".into(), "Bar".into())]);
    /// assert_eq!(request.body(), &[1, 2, 3]);
    /// assert_eq!(request.certificate_version(), Some(2));
    /// ```
    #[inline]
    pub fn build(self) -> HttpRequest<'a> {
        HttpRequest {
            method: self.method.unwrap_or(Method::GET.into()),
            url: self.url.unwrap_or("/".to_string()),
            headers: self.headers,
            body: self.body,
            certificate_version: self.certificate_version,
        }
    }

    /// Build an [HttpUpdateRequest] from the builder.
    ///
    /// If the method is not set, it will default to `"GET"`.
    /// If the URL is not set, it will default to `"/"`.
    /// If the headers or body are not set, they will default to empty arrays.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::{HttpRequestBuilder, Method};
    ///
    /// let update_request = HttpRequestBuilder::new()
    ///     .with_method(Method::GET)
    ///     .with_url("/")
    ///     .with_headers(vec![("X-Custom-Foo".into(), "Bar".into())])
    ///     .with_body(&[1, 2, 3])
    ///     .build_update();
    ///
    /// assert_eq!(update_request.method(), Method::GET);
    /// assert_eq!(update_request.url(), "/");
    /// assert_eq!(update_request.headers(), &[("X-Custom-Foo".into(), "Bar".into())]);
    /// assert_eq!(update_request.body(), &[1, 2, 3]);
    /// ```
    #[inline]
    pub fn build_update(self) -> HttpUpdateRequest<'a> {
        HttpUpdateRequest {
            method: self.method.unwrap_or(Method::GET.into()),
            url: self.url.unwrap_or("/".to_string()),
            headers: self.headers,
            body: self.body,
        }
    }
}

/// A Candid-encodable representation of an HTTP update request. This struct is
/// used by the `http_update_request` method of the HTTP Gateway Protocol.
///
/// This is the same as [HttpRequest], excluding the
/// [certificate_version](HttpRequest::certificate_version) property.
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpUpdateRequest, HttpRequest, Method};
///
/// let request = HttpRequest::get("/")
///     .with_method(Method::GET)
///     .with_url("/")
///     .with_headers(vec![("X-Custom-Foo".into(), "Bar".into())])
///     .with_body(&[1, 2, 3])
///     .with_certificate_version(2)
///     .build();
/// let update_request = HttpUpdateRequest::from(request);
///
/// assert_eq!(update_request.method(), Method::GET);
/// assert_eq!(update_request.url(), "/");
/// assert_eq!(update_request.headers(), &[("X-Custom-Foo".into(), "Bar".into())]);
/// assert_eq!(update_request.body(), &[1, 2, 3]);
/// ```
#[derive(Clone, Debug, CandidType, Deserialize, PartialEq, Eq)]
pub struct HttpUpdateRequest<'a> {
    /// HTTP request method.
    method: MethodWrapper,

    /// HTTP request URL.
    url: String,

    /// HTTP request headers.
    headers: Vec<HeaderField>,

    /// HTTP request body as an array of bytes.
    body: Cow<'a, [u8]>,
}

impl<'a> HttpUpdateRequest<'a> {
    /// Returns the HTTP method of the request.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("/").build_update();
    ///
    /// assert_eq!(request.method(), "GET");
    /// ```
    #[inline]
    pub fn method(&self) -> &Method {
        &self.method.0
    }

    /// Returns the URL of the request.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("/").build_update();
    ///
    /// assert_eq!(request.url(), "/");
    /// ```
    #[inline]
    pub fn url(&self) -> &str {
        &self.url
    }

    /// Returns the headers of the request.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("/")
    ///     .with_headers(vec![("Accept".into(), "text/plain".into())])
    ///     .build_update();
    ///
    /// assert_eq!(request.headers(), &[("Accept".into(), "text/plain".into())]);
    /// ```
    #[inline]
    pub fn headers(&self) -> &[HeaderField] {
        &self.headers
    }

    /// Returns the body of the request.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("/")
    ///     .with_body(&[1, 2, 3])
    ///     .build_update();
    ///
    /// assert_eq!(request.body(), &[1, 2, 3]);
    /// ```
    #[inline]
    pub fn body(&self) -> &[u8] {
        &self.body
    }

    /// Returns the path of the request URL, without domain, query parameters or fragments.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("https://canister.com/sample-asset.txt").build();
    ///
    /// assert_eq!(request.get_path().unwrap(), "/sample-asset.txt");
    /// ```
    pub fn get_path(&self) -> HttpCertificationResult<String> {
        let uri = self
            .url
            .parse::<Uri>()
            .map_err(|_| HttpCertificationError::MalformedUrl(self.url.to_string()))?;

        let decoded_path = urlencoding::decode(uri.path()).map(|path| path.into_owned())?;
        Ok(decoded_path)
    }

    /// Returns the query parameters of the request URL, if any, as a string.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_http_certification::HttpRequest;
    ///
    /// let request = HttpRequest::get("https://canister.com/sample-asset.txt?foo=bar").build();
    ///
    /// assert_eq!(request.get_query().unwrap(), Some("foo=bar".to_string()));
    /// ```
    pub fn get_query(&self) -> HttpCertificationResult<Option<String>> {
        self.url
            .parse::<Uri>()
            .map(|uri| uri.query().map(|uri| uri.to_owned()))
            .map_err(|_| HttpCertificationError::MalformedUrl(self.url.to_string()))
    }
}

impl<'a> From<HttpRequest<'a>> for HttpUpdateRequest<'a> {
    fn from(req: HttpRequest<'a>) -> Self {
        HttpUpdateRequest {
            method: req.method,
            url: req.url,
            headers: req.headers,
            body: req.body,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn request_get_uri() {
        let req = HttpRequest::get("https://canister.com/sample-asset.txt").build();

        let path = req.get_path().unwrap();
        let query = req.get_query().unwrap();

        assert_eq!(path, "/sample-asset.txt");
        assert!(query.is_none());
    }

    #[test]
    fn request_get_encoded_uri() {
        let test_requests = [
            (
                HttpRequest::get("https://canister.com/%73ample-asset.txt").build(),
                "/sample-asset.txt",
                "",
            ),
            (
                HttpRequest::get("https://canister.com/path/123?foo=test%20component&bar=1").build(),
                "/path/123",
                "foo=test%20component&bar=1",
            ),
            (
                HttpRequest::get("https://canister.com/a%20file.txt").build(),
                "/a file.txt",
                "",
            ),
            (
                HttpRequest::get("https://canister.com/mujin0722/3888-zjfrd-tqaaa-aaaaf-qakia-cai/%E6%97%A0%E8%AE%BA%E7%BE%8E%E8%81%94%E5%82%A8%E6%98%AF%E5%90%A6%E5%8A%A0%E6%81%AFbtc%E4%BB%8D%E5%B0%86%E5%9B%9E%E5%88%B07%E4%B8%87%E5%88%80").build(),
                "/mujin0722/3888-zjfrd-tqaaa-aaaaf-qakia-cai/无论美联储是否加息btc仍将回到7万刀",
                "",
            ),
        ];

        for (req, expected_path, expected_query) in test_requests.iter() {
            let path = req.get_path().unwrap();
            let query = req.get_query().unwrap();

            assert_eq!(path, *expected_path);
            assert_eq!(query.unwrap_or_default(), *expected_query);
        }
    }
}