ic-asset-router 0.1.1

File-based HTTP routing with IC response certification for Internet Computer canisters
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
use std::collections::HashMap;

use ic_http_certification::{HeaderField, Method};

/// Error returned by [`RouteContext::json()`].
#[derive(Debug)]
pub enum JsonBodyError {
    /// The body bytes are not valid UTF-8.
    Utf8(std::str::Utf8Error),
    /// JSON deserialization failed.
    Json(serde_json::Error),
}

impl std::fmt::Display for JsonBodyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Utf8(e) => write!(f, "body is not valid UTF-8: {e}"),
            Self::Json(e) => write!(f, "JSON deserialization failed: {e}"),
        }
    }
}

impl std::error::Error for JsonBodyError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Utf8(e) => Some(e),
            Self::Json(e) => Some(e),
        }
    }
}

/// Error returned by [`RouteContext::form()`].
#[derive(Debug)]
pub enum FormBodyError {
    /// The body bytes are not valid UTF-8.
    Utf8(std::str::Utf8Error),
    /// Form deserialization failed.
    Deserialize(serde_urlencoded::de::Error),
}

impl std::fmt::Display for FormBodyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Utf8(e) => write!(f, "body is not valid UTF-8: {e}"),
            Self::Deserialize(e) => write!(f, "form deserialization failed: {e}"),
        }
    }
}

impl std::error::Error for FormBodyError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Utf8(e) => Some(e),
            Self::Deserialize(e) => Some(e),
        }
    }
}

/// A type alias for query string parameters parsed from the URL.
pub type QueryParams = HashMap<String, String>;

/// A context object bundling all request data for route handlers.
///
/// Rather than accumulating positional arguments as features grow (params, query
/// strings, method, headers, etc.), handlers receive a single context object.
/// This is extensible — new fields can be added without changing every handler
/// signature.
///
/// The type parameter `P` is the typed params struct generated by the build
/// script for each route. Routes without dynamic segments use `()`.
///
/// The type parameter `S` is the typed search (query string) params struct.
/// Routes that define a `pub struct SearchParams` (implementing
/// `serde::Deserialize`) get the query string deserialized into `ctx.search`.
/// Routes without a `SearchParams` struct default to `S = ()`.
///
/// Untyped query access is always available via `ctx.query` regardless of `S`.
///
/// # Examples
///
/// A handler for a static route (no path parameters or search params):
///
/// ```rust,ignore
/// use ic_asset_router::{RouteContext, HttpResponse};
///
/// pub fn get(ctx: RouteContext<()>) -> HttpResponse<'static> {
///     let url = &ctx.url;
///     let method = &ctx.method;
///     // Access untyped query params:
///     let page = ctx.query.get("page").cloned().unwrap_or_default();
///     // ... build response
///     # todo!()
/// }
/// ```
///
/// A handler for a dynamic route with typed params (e.g. `_postId/index.rs`):
///
/// ```rust,ignore
/// use ic_asset_router::{RouteContext, HttpResponse};
///
/// // Generated by the build script in mod.rs:
/// // pub struct Params { pub post_id: String }
///
/// pub fn get(ctx: RouteContext<Params>) -> HttpResponse<'static> {
///     let post_id = &ctx.params.post_id;
///     // ... build response using post_id
///     # todo!()
/// }
/// ```
pub struct RouteContext<P, S = ()> {
    /// Typed route parameters extracted from the URL path.
    pub params: P,
    /// Typed search (query string) parameters deserialized from the URL.
    ///
    /// Populated by `serde_urlencoded` when the route defines a `SearchParams`
    /// struct. Defaults to `()` for routes without typed search params.
    pub search: S,
    /// Query string parameters parsed from the URL (untyped, always available).
    pub query: QueryParams,
    /// The HTTP method of the request.
    pub method: Method,
    /// The request headers.
    pub headers: Vec<HeaderField>,
    /// The raw request body bytes.
    pub body: Vec<u8>,
    /// The full request URL.
    pub url: String,
    /// The wildcard capture for catch-all routes.
    ///
    /// `None` for routes without a wildcard segment.
    /// `Some("docs/report.pdf")` for a request to `/files/docs/report.pdf`
    /// matching `/files/*`.
    pub wildcard: Option<String>,
}

impl<P, S> RouteContext<P, S> {
    /// Returns the value of the first header matching `name` (case-insensitive).
    ///
    /// Returns `None` if no header with that name exists.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let auth = ctx.header("authorization"); // Option<&str>
    /// let ct = ctx.header("Content-Type");    // case-insensitive
    /// ```
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }

    /// Returns the request body as a UTF-8 string.
    ///
    /// Returns `Err` if the body is not valid UTF-8. For lossy conversion,
    /// use `String::from_utf8_lossy(&ctx.body)` directly.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// match ctx.body_to_str() {
    ///     Ok(text) => { /* use text */ }
    ///     Err(_) => { /* return 400 */ }
    /// }
    /// ```
    pub fn body_to_str(&self) -> Result<&str, std::str::Utf8Error> {
        std::str::from_utf8(&self.body)
    }

    /// Deserializes the request body as JSON into type `T`.
    ///
    /// Returns `Err` if the body is not valid UTF-8 or if JSON
    /// deserialization fails.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// #[derive(serde::Deserialize)]
    /// struct CreateItem { name: String }
    ///
    /// pub fn post(ctx: RouteContext<()>) -> HttpResponse<'static> {
    ///     let input: CreateItem = match ctx.json() {
    ///         Ok(v) => v,
    ///         Err(_) => return bad_request("invalid JSON body"),
    ///     };
    ///     // ...
    ///     # todo!()
    /// }
    /// ```
    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, JsonBodyError> {
        let text = std::str::from_utf8(&self.body).map_err(JsonBodyError::Utf8)?;
        serde_json::from_str(text).map_err(JsonBodyError::Json)
    }

    /// Parses the request body as `application/x-www-form-urlencoded` key-value
    /// pairs.
    ///
    /// Convenience wrapper around [`parse_form_body`]. Uses lossy UTF-8
    /// conversion and skips malformed pairs, so it never fails.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let fields = ctx.form_data();
    /// let author = fields.get("author").cloned().unwrap_or_default();
    /// ```
    pub fn form_data(&self) -> HashMap<String, String> {
        parse_form_body(&self.body)
    }

    /// Deserializes the request body as `application/x-www-form-urlencoded`
    /// into type `T`.
    ///
    /// Returns `Err` if the body is not valid UTF-8 or if deserialization
    /// fails.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// #[derive(serde::Deserialize)]
    /// struct CommentForm { author: String, body: String }
    ///
    /// pub fn post(ctx: RouteContext<Params>) -> HttpResponse<'static> {
    ///     let form: CommentForm = match ctx.form() {
    ///         Ok(v) => v,
    ///         Err(_) => return bad_request("invalid form data"),
    ///     };
    ///     // ...
    ///     # todo!()
    /// }
    /// ```
    pub fn form<T: serde::de::DeserializeOwned>(&self) -> Result<T, FormBodyError> {
        let text = std::str::from_utf8(&self.body).map_err(FormBodyError::Utf8)?;
        serde_urlencoded::from_str(text).map_err(FormBodyError::Deserialize)
    }
}

/// Parse query string key-value pairs from a URL.
///
/// Extracts the portion after `?` and splits on `&` to produce key-value pairs.
/// Keys and values are URL-decoded. Malformed pairs (missing `=`) are skipped.
///
/// Returns an empty map if there is no query string.
pub fn parse_query(url: &str) -> QueryParams {
    let query_str = match url.split_once('?') {
        Some((_, q)) => q,
        None => return QueryParams::new(),
    };

    // Strip fragment if present (e.g. `?page=1#section`)
    let query_str = query_str.split_once('#').map_or(query_str, |(q, _)| q);

    query_str
        .split('&')
        .filter(|s| !s.is_empty())
        .filter_map(|pair| {
            let (key, value) = pair.split_once('=')?;
            Some((url_decode(key).into_owned(), url_decode(value).into_owned()))
        })
        .collect()
}

/// Percent-decode a URL-encoded string.
///
/// Decodes `%XX` hex sequences and converts `+` to space, as used in both
/// query strings and `application/x-www-form-urlencoded` bodies. Returns a
/// borrowed `Cow` when the input contains no encoded characters (zero-copy
/// fast path). Does not validate UTF-8 beyond what `String::from_utf8_lossy`
/// handles — malformed `%XX` sequences (e.g. `%ZZ`) are passed through
/// literally.
///
/// # Examples
///
/// ```
/// use ic_asset_router::url_decode;
///
/// assert_eq!(url_decode("hello%20world"), "hello world");
/// assert_eq!(url_decode("a+b"), "a b");
/// assert_eq!(url_decode("plain"), "plain");
/// ```
pub fn url_decode(input: &str) -> std::borrow::Cow<'_, str> {
    if !input.contains('%') && !input.contains('+') {
        return std::borrow::Cow::Borrowed(input);
    }

    let mut bytes = Vec::with_capacity(input.len());
    let mut chars = input.bytes();
    while let Some(b) = chars.next() {
        match b {
            b'+' => bytes.push(b' '),
            b'%' => {
                let hi = chars.next().and_then(hex_val);
                let lo = chars.next().and_then(hex_val);
                match (hi, lo) {
                    (Some(h), Some(l)) => bytes.push(h << 4 | l),
                    _ => {
                        // Malformed percent encoding — pass through literally
                        bytes.push(b'%');
                    }
                }
            }
            _ => bytes.push(b),
        }
    }

    String::from_utf8(bytes)
        .map(std::borrow::Cow::Owned)
        .unwrap_or_else(|e| {
            std::borrow::Cow::Owned(String::from_utf8_lossy(e.as_bytes()).into_owned())
        })
}

/// Deserialize a URL query string into a typed struct using `serde_urlencoded`.
///
/// This is the helper used by the generated route wiring to populate
/// `RouteContext.search`. If deserialization fails (missing required fields,
/// type mismatches, malformed encoding), returns `S::default()` so that
/// handlers never see a panic from bad query strings.
///
/// The type `S` must implement both `serde::Deserialize` and `Default`.
pub fn deserialize_search_params<S>(query_str: &str) -> S
where
    S: serde::de::DeserializeOwned + Default,
{
    // Strip leading '?' if present (the caller may pass the raw query portion
    // or the full `?key=val` string).
    let qs = query_str.strip_prefix('?').unwrap_or(query_str);
    serde_urlencoded::from_str(qs).unwrap_or_default()
}

/// Parse an `application/x-www-form-urlencoded` body into key-value pairs.
///
/// This is the encoding used by HTML `<form>` submissions. The body is
/// interpreted as UTF-8, split on `&`, and each `key=value` pair is
/// URL-decoded. Pairs without `=` are skipped.
///
/// # Examples
///
/// ```
/// use ic_asset_router::parse_form_body;
///
/// let fields = parse_form_body(b"name=Alice&age=30");
/// assert_eq!(fields.get("name").unwrap(), "Alice");
/// assert_eq!(fields.get("age").unwrap(), "30");
///
/// let fields = parse_form_body(b"q=hello+world");
/// assert_eq!(fields.get("q").unwrap(), "hello world");
/// ```
pub fn parse_form_body(body: &[u8]) -> HashMap<String, String> {
    let input = String::from_utf8_lossy(body);
    input
        .split('&')
        .filter(|s| !s.is_empty())
        .filter_map(|pair| {
            let (key, value) = pair.split_once('=')?;
            Some((url_decode(key).into_owned(), url_decode(value).into_owned()))
        })
        .collect()
}

fn hex_val(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

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

    #[test]
    fn parse_query_basic() {
        let q = parse_query("http://example.com/path?page=3&filter=active");
        assert_eq!(q.get("page").unwrap(), "3");
        assert_eq!(q.get("filter").unwrap(), "active");
    }

    #[test]
    fn parse_query_empty_url() {
        let q = parse_query("");
        assert!(q.is_empty());
    }

    #[test]
    fn parse_query_no_query_string() {
        let q = parse_query("/path/to/resource");
        assert!(q.is_empty());
    }

    #[test]
    fn parse_query_empty_query_string() {
        let q = parse_query("/path?");
        assert!(q.is_empty());
    }

    #[test]
    fn parse_query_with_fragment() {
        let q = parse_query("/path?page=1#section");
        assert_eq!(q.get("page").unwrap(), "1");
        assert_eq!(q.len(), 1);
    }

    #[test]
    fn parse_query_url_encoded_values() {
        let q = parse_query("/search?q=hello+world&name=foo%20bar");
        assert_eq!(q.get("q").unwrap(), "hello world");
        assert_eq!(q.get("name").unwrap(), "foo bar");
    }

    #[test]
    fn parse_query_skips_malformed_pairs() {
        // Pairs without `=` are skipped
        let q = parse_query("/path?good=yes&bad&also=fine");
        assert_eq!(q.get("good").unwrap(), "yes");
        assert_eq!(q.get("also").unwrap(), "fine");
        assert_eq!(q.len(), 2);
    }

    #[test]
    fn parse_query_empty_value() {
        let q = parse_query("/path?key=");
        assert_eq!(q.get("key").unwrap(), "");
    }

    #[test]
    fn parse_query_multiple_equals() {
        // Only splits on the first `=`
        let q = parse_query("/path?expr=a=b");
        assert_eq!(q.get("expr").unwrap(), "a=b");
    }

    // --- 5.3.5: parse_query with valid params (bare query string) ---

    #[test]
    fn parse_query_bare_query_string() {
        // Tests the specific input `?page=3&filter=active` — note: parse_query
        // expects a URL (or URL path), so `?page=3&filter=active` works since
        // it splits on `?`.
        let q = parse_query("?page=3&filter=active");
        assert_eq!(q.get("page").unwrap(), "3");
        assert_eq!(q.get("filter").unwrap(), "active");
    }

    // --- 5.3.6: parse_query with empty string ---

    #[test]
    fn parse_query_empty_string_returns_empty_hashmap() {
        let q = parse_query("");
        assert!(q.is_empty());
    }

    // --- 5.3.7: malformed query values don't panic (typed search params) ---

    #[test]
    fn deserialize_search_params_valid() {
        #[derive(serde::Deserialize, Default, Debug)]
        struct Sp {
            page: Option<u32>,
            filter: Option<String>,
        }

        let sp: Sp = deserialize_search_params("page=3&filter=active");
        assert_eq!(sp.page, Some(3));
        assert_eq!(sp.filter.as_deref(), Some("active"));
    }

    #[test]
    fn deserialize_search_params_type_mismatch_falls_back() {
        // `page=abc` can't parse as u32 — the entire deserialization fails and
        // falls back to Default, giving None for all fields.
        #[derive(serde::Deserialize, Default, Debug)]
        struct Sp {
            page: Option<u32>,
            filter: Option<String>,
        }

        let sp: Sp = deserialize_search_params("page=abc&filter=active");
        // serde_urlencoded fails the whole parse on type mismatch, so we get defaults.
        assert_eq!(sp.page, None);
        assert_eq!(sp.filter, None);
    }

    #[test]
    fn deserialize_search_params_empty_string() {
        #[derive(serde::Deserialize, Default, Debug)]
        struct Sp {
            page: Option<u32>,
        }

        let sp: Sp = deserialize_search_params("");
        assert_eq!(sp.page, None);
    }

    #[test]
    fn deserialize_search_params_missing_fields_default_to_none() {
        #[derive(serde::Deserialize, Default, Debug)]
        struct Sp {
            page: Option<u32>,
            filter: Option<String>,
            limit: Option<u32>,
        }

        let sp: Sp = deserialize_search_params("page=5");
        assert_eq!(sp.page, Some(5));
        assert_eq!(sp.filter, None);
        assert_eq!(sp.limit, None);
    }

    #[test]
    fn deserialize_search_params_with_leading_question_mark() {
        #[derive(serde::Deserialize, Default, Debug)]
        struct Sp {
            page: Option<u32>,
        }

        let sp: Sp = deserialize_search_params("?page=7");
        assert_eq!(sp.page, Some(7));
    }

    #[test]
    fn deserialize_search_params_malformed_encoding_does_not_panic() {
        #[derive(serde::Deserialize, Default, Debug)]
        struct Sp {
            q: Option<String>,
        }

        // Malformed percent encoding — should not panic, falls back to default.
        let sp: Sp = deserialize_search_params("q=%ZZ");
        // serde_urlencoded may handle this gracefully or fail; either way, no panic.
        let _ = sp.q;
    }

    // --- 6.8: url_decode tests ---

    #[test]
    fn url_decode_percent_encoding() {
        assert_eq!(url_decode("hello%20world"), "hello world");
    }

    #[test]
    fn url_decode_plus_as_space() {
        assert_eq!(url_decode("a+b"), "a b");
    }

    #[test]
    fn url_decode_malformed_passthrough() {
        // `%en` — `e` is valid hex but `n` is not. The implementation consumes
        // both bytes after `%` and only emits `%` for the malformed sequence,
        // so the two consumed chars are lost: "no%encoding" → "no%coding".
        assert_eq!(url_decode("no%encoding"), "no%coding");
    }

    #[test]
    fn url_decode_plain_passthrough() {
        let result = url_decode("plain");
        assert_eq!(result, "plain");
        // Should be zero-copy (borrowed)
        assert!(matches!(result, std::borrow::Cow::Borrowed(_)));
    }

    // --- 8.2.4: url_decode with invalid UTF-8 byte sequences ---

    #[test]
    fn url_decode_invalid_utf8_returns_valid_string() {
        // %FF%FE are not valid UTF-8 bytes. url_decode should produce a
        // valid string (via lossy conversion) without panicking or leaking.
        let result = url_decode("%FF%FE");
        // The result should be a valid Rust string (no panic).
        assert!(!result.is_empty());
        // String::from_utf8_lossy replaces invalid sequences with U+FFFD.
        assert!(result.contains('\u{FFFD}'));
    }

    // --- 8.6.1: url_decode edge case tests ---

    #[test]
    fn url_decode_trailing_percent() {
        // Trailing '%' with no hex digits after it → pass through literally.
        assert_eq!(url_decode("abc%"), "abc%");
    }

    #[test]
    fn url_decode_only_percent() {
        // A lone '%' at end of string → pass through literally.
        assert_eq!(url_decode("%"), "%");
    }

    #[test]
    fn url_decode_percent_one_hex_then_eof() {
        // '%' followed by one valid hex char then EOF — malformed, the '%' is
        // kept but the consumed hex char is lost (consistent with the existing
        // malformed-passthrough behaviour documented in url_decode_malformed_passthrough).
        assert_eq!(url_decode("abc%4"), "abc%");
    }

    #[test]
    fn url_decode_null_byte() {
        // "%00" decodes to a null byte (U+0000).
        let result = url_decode("%00");
        assert_eq!(result, "\0");
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn url_decode_double_encoded() {
        // "%2520" → single decode produces "%20" (not a space).
        // The first pass decodes %25 → '%', leaving "20" as literal.
        assert_eq!(url_decode("%2520"), "%20");
    }

    #[test]
    fn url_decode_empty_string() {
        let result = url_decode("");
        assert_eq!(result, "");
        // Empty string has no '%' or '+', so it should be zero-copy.
        assert!(matches!(result, std::borrow::Cow::Borrowed(_)));
    }

    // --- 6.8: parse_form_body tests ---

    #[test]
    fn parse_form_body_basic_pairs() {
        let fields = parse_form_body(b"name=Alice&age=30");
        assert_eq!(fields.get("name").unwrap(), "Alice");
        assert_eq!(fields.get("age").unwrap(), "30");
    }

    #[test]
    fn parse_form_body_plus_decoding() {
        let fields = parse_form_body(b"q=hello+world");
        assert_eq!(fields.get("q").unwrap(), "hello world");
    }

    #[test]
    fn parse_form_body_empty() {
        let fields = parse_form_body(b"");
        assert!(fields.is_empty());
    }

    #[test]
    fn parse_form_body_encoded_values() {
        let fields = parse_form_body(b"key=val%26ue");
        assert_eq!(fields.get("key").unwrap(), "val&ue");
    }

    // --- 7.7: RouteContext convenience method tests ---

    fn test_ctx(headers: Vec<(String, String)>, body: Vec<u8>) -> RouteContext<()> {
        RouteContext {
            params: (),
            search: (),
            query: QueryParams::new(),
            method: Method::GET,
            headers,
            body,
            url: String::new(),
            wildcard: None,
        }
    }

    // header tests

    #[test]
    fn header_case_insensitive() {
        let ctx = test_ctx(
            vec![("authorization".to_string(), "Bearer x".to_string())],
            vec![],
        );
        assert_eq!(ctx.header("Authorization"), Some("Bearer x"));
        assert_eq!(ctx.header("authorization"), Some("Bearer x"));
        assert_eq!(ctx.header("AUTHORIZATION"), Some("Bearer x"));
    }

    #[test]
    fn header_missing() {
        let ctx = test_ctx(vec![], vec![]);
        assert_eq!(ctx.header("x-missing"), None);
    }

    #[test]
    fn header_first_match_wins() {
        let ctx = test_ctx(
            vec![
                ("x-custom".to_string(), "first".to_string()),
                ("x-custom".to_string(), "second".to_string()),
            ],
            vec![],
        );
        assert_eq!(ctx.header("x-custom"), Some("first"));
    }

    // body_to_str tests

    #[test]
    fn body_to_str_valid_utf8() {
        let ctx = test_ctx(vec![], b"hello".to_vec());
        assert_eq!(ctx.body_to_str(), Ok("hello"));
    }

    #[test]
    fn body_to_str_invalid_utf8() {
        let ctx = test_ctx(vec![], vec![0xff, 0xfe]);
        assert!(ctx.body_to_str().is_err());
    }

    #[test]
    fn body_to_str_empty() {
        let ctx = test_ctx(vec![], vec![]);
        assert_eq!(ctx.body_to_str(), Ok(""));
    }

    // json tests

    #[test]
    fn json_valid() {
        #[derive(serde::Deserialize, Debug, PartialEq)]
        struct Item {
            name: String,
        }
        let ctx = test_ctx(vec![], br#"{"name":"test"}"#.to_vec());
        let result: Result<Item, _> = ctx.json();
        assert_eq!(
            result.unwrap(),
            Item {
                name: "test".to_string()
            }
        );
    }

    #[test]
    fn json_invalid_json() {
        #[derive(serde::Deserialize)]
        struct Item {
            #[allow(dead_code)]
            name: String,
        }
        let ctx = test_ctx(vec![], b"{invalid}".to_vec());
        let result: Result<Item, _> = ctx.json();
        assert!(matches!(result, Err(JsonBodyError::Json(_))));
    }

    #[test]
    fn json_invalid_utf8() {
        #[derive(serde::Deserialize)]
        struct Item {
            #[allow(dead_code)]
            name: String,
        }
        let ctx = test_ctx(vec![], vec![0xff, 0xfe]);
        let result: Result<Item, _> = ctx.json();
        assert!(matches!(result, Err(JsonBodyError::Utf8(_))));
    }

    #[test]
    fn json_empty_body() {
        #[derive(serde::Deserialize)]
        struct Item {
            #[allow(dead_code)]
            name: String,
        }
        let ctx = test_ctx(vec![], vec![]);
        let result: Result<Item, _> = ctx.json();
        assert!(matches!(result, Err(JsonBodyError::Json(_))));
    }

    // form_data tests

    #[test]
    fn form_data_basic() {
        let ctx = test_ctx(vec![], b"name=Alice&age=30".to_vec());
        let fields = ctx.form_data();
        assert_eq!(fields.get("name").unwrap(), "Alice");
        assert_eq!(fields.get("age").unwrap(), "30");
    }

    #[test]
    fn form_data_empty() {
        let ctx = test_ctx(vec![], vec![]);
        let fields = ctx.form_data();
        assert!(fields.is_empty());
    }

    #[test]
    fn form_data_url_encoded() {
        let ctx = test_ctx(vec![], b"greeting=hello+world&path=%2Ffoo%2Fbar".to_vec());
        let fields = ctx.form_data();
        assert_eq!(fields.get("greeting").unwrap(), "hello world");
        assert_eq!(fields.get("path").unwrap(), "/foo/bar");
    }

    // form tests

    #[test]
    fn form_valid() {
        #[derive(serde::Deserialize, Debug, PartialEq)]
        struct Comment {
            author: String,
            body: String,
        }
        let ctx = test_ctx(vec![], b"author=Alice&body=hello".to_vec());
        let result: Result<Comment, _> = ctx.form();
        assert_eq!(
            result.unwrap(),
            Comment {
                author: "Alice".to_string(),
                body: "hello".to_string(),
            }
        );
    }

    #[test]
    fn form_missing_field() {
        #[derive(serde::Deserialize)]
        struct Comment {
            #[allow(dead_code)]
            author: String,
            #[allow(dead_code)]
            body: String,
        }
        let ctx = test_ctx(vec![], b"author=Alice".to_vec());
        let result: Result<Comment, _> = ctx.form();
        assert!(matches!(result, Err(FormBodyError::Deserialize(_))));
    }

    #[test]
    fn form_invalid_utf8() {
        #[derive(serde::Deserialize)]
        struct Comment {
            #[allow(dead_code)]
            author: String,
        }
        let ctx = test_ctx(vec![], vec![0xff, 0xfe]);
        let result: Result<Comment, _> = ctx.form();
        assert!(matches!(result, Err(FormBodyError::Utf8(_))));
    }

    #[test]
    fn form_empty_body_with_optional_fields() {
        #[derive(serde::Deserialize, Debug, PartialEq)]
        struct Opts {
            name: Option<String>,
        }
        let ctx = test_ctx(vec![], vec![]);
        let result: Result<Opts, _> = ctx.form();
        assert_eq!(result.unwrap(), Opts { name: None });
    }
}