aex 0.1.6

A web server for 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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
#[cfg(test)]
mod tests {
    use std::{
        net::SocketAddr,
        sync::{
            Arc,
            atomic::{AtomicUsize, Ordering},
        },
        time::Duration,
    };

    use aex::{
        connection::context::{Context, TypeMapExt},
        exe,
        http::{
            meta::HttpMetadata,
            protocol::{header::HeaderKey, status::StatusCode},
            router::{NodeType, Router},
            types::{Executor, to_executor},
        },
        server::{HTTPServer, Server},
        tcp::types::{Command, RawCodec},
    };
    use futures::FutureExt;
    use tokio::time::sleep;

    #[test]
    fn test_header_key_standard_match() {
        // 测试标准 Header 是否能准确解析并还原
        let cases = [
            ("Content-Type", HeaderKey::ContentType),
            ("Host", HeaderKey::Host),
            ("Authorization", HeaderKey::Authorization),
        ];

        for (input, expected_variant) in cases {
            let parsed = HeaderKey::from_str(input).unwrap();
            assert_eq!(parsed, expected_variant);
            assert_eq!(parsed.as_str(), input);
        }
    }

    #[test]
    fn test_header_key_case_insensitivity() {
        // 验证大小写不敏感解析
        let mixed_cases = ["content-type", "CONTENT-TYPE", "CoNtEnT-TyPe"];
        for input in mixed_cases {
            let parsed = HeaderKey::from_str(input).unwrap();
            assert_eq!(parsed, HeaderKey::ContentType);
            // 无论输入如何,as_str() 应当返回宏定义的标准规范格式
            assert_eq!(parsed.as_str(), "Content-Type");
        }
    }

    #[test]
    fn test_header_key_custom_fallback() {
        // 验证非标准 Header 是否自动转为 Custom 变体
        let custom_name = "X-My-Custom-Header";
        let parsed = HeaderKey::from_str(custom_name).unwrap();

        match &parsed {
            HeaderKey::Custom(s) => assert_eq!(s, custom_name),
            _ => panic!("应当匹配为 Custom 变体"),
        }

        assert_eq!(parsed.as_str(), custom_name);
    }

    #[test]
    fn test_header_key_display_trait() {
        // 验证 Display 实现是否正确调用了 as_str
        let key = HeaderKey::UserAgent;
        assert_eq!(format!("{}", key), "User-Agent");

        let custom = HeaderKey::Custom("X-Foo".to_string());
        assert_eq!(format!("{}", custom), "X-Foo");
    }

    #[test]
    fn test_header_key_roundtrip() {
        // 验证:字符串 -> 枚举 -> 字符串 的完整性
        // 测试标准键(宏内部会进行 to_ascii_lowercase 匹配)
        let raw_standard = "Accept-Encoding";
        let key = HeaderKey::from_str(raw_standard).unwrap();
        assert_eq!(key.as_str(), raw_standard);

        // 测试自定义键
        let raw_custom = "X-Tracing-Id";
        let key_custom = HeaderKey::from_str(raw_custom).unwrap();
        assert_eq!(key_custom.as_str(), raw_custom);
    }

    #[test]
    fn test_header_key_trimming() {
        // 验证 from_str 是否正确处理空格
        let input = "  Content-Type  ";
        let parsed = HeaderKey::from_str(input).unwrap();
        assert_eq!(parsed, HeaderKey::ContentType);
    }

    #[tokio::test]
    async fn test_server_auto_parsing_and_routing() {
        // 1. 构建 Router 场景
        let mut hr = Router::new(NodeType::Static("root".into()));

        hr.insert(
            "/api/user/:id",
            Some("GET"),
            Arc::new(|ctx: &mut Context| {
                async move {
                    let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();
                    let user_id = meta
                        .params
                        .as_ref()
                        .and_then(|p| p.data.as_ref())
                        .and_then(|d| d.get("id"))
                        .cloned()
                        .unwrap_or_default();

                    let custom_key = HeaderKey::from_str("X-Aex-Auth").unwrap();
                    let auth_val = meta.headers.get(&custom_key).cloned().unwrap_or_default();

                    meta.status = StatusCode::Ok;
                    meta.body = format!("User:{}, Auth:{}", user_id, auth_val).into_bytes();

                    ctx.local.set_value(meta);
                    true
                }
                .boxed()
            }),
            None,
        );

        // 2. 初始化端口并启动 Server
        // 获取一个空闲端口
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
        let actual_addr = listener.local_addr().unwrap();
        drop(listener); // 释放端口给 Server

        let server = Server::new(actual_addr, None);
        let server = server.http(hr).clone();

        tokio::spawn(async move {
            if let Err(e) = server.start().await {
                eprintln!("Server exit: {}", e);
            }
        });

        // 3. 关键改进:使用 tokio::time::sleep 并增加连接重试逻辑
        let client = reqwest::Client::new();
        let mut res = None;
        let url = format!("http://{}/api/user/9527", actual_addr);

        // 最多等待 1 秒 (100ms * 10)
        for _ in 0..10 {
            tokio::time::sleep(Duration::from_millis(100)).await;
            match client
                .get(&url)
                .header("X-Aex-Auth", "secret-token-v3")
                .send()
                .await
            {
                Ok(response) => {
                    res = Some(response);
                    break;
                }
                Err(_) => continue, // Server 可能还没准备好
            }
        }

        let res = res.expect("服务器在重试多次后仍未就绪 (Connection Refused)");

        // 4. 最终验证
        assert_eq!(res.status().as_u16(), 200);
        let body = res.text().await.unwrap();
        assert_eq!(body, "User:9527, Auth:secret-token-v3");

        println!("✅ Server 全链路 Router 自动化集成测试通过!");
    }

    #[tokio::test]
    async fn test_full_stack_wildcard_and_middleware() {
        // --- 1. 准备共享状态用于验证 ---
        let mw_exec_order = Arc::new(std::sync::Mutex::new(Vec::new()));
        let wildcard_hit_count = Arc::new(AtomicUsize::new(0));

        // --- 2. 构建 Router 场景 ---
        let mut hr = Router::new(NodeType::Static("root".into()));

        // A. 注册中间件 A (记录轨迹)
        let t1 = mw_exec_order.clone();

        // B. 注册中间件 B (记录轨迹并允许通过)
        let t2 = mw_exec_order.clone();

        // 2. 在定义中间件时,显式指定其返回值类型
        let mw_a: Arc<Executor> = Arc::new(move |_ctx| {
            let t = t1.clone();
            async move {
                t.lock().unwrap().push("MW_A");
                true
            }
            .boxed()
        });

        let mw_b: Arc<Executor> = Arc::new(move |_ctx| {
            let t = t2.clone();
            async move {
                t.lock().unwrap().push("MW_B");
                true
            }
            .boxed()
        });

        // C. 注册通配符路由处理器
        let count = wildcard_hit_count.clone();
        hr.insert(
            "/assets/*",
            Some("GET"),
            Arc::new(move |ctx: &mut Context| {
                let c = count.clone();
                async move {
                    c.fetch_add(1, Ordering::SeqCst);
                    let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();
                    meta.status = StatusCode::Ok;
                    meta.body = b"Wildcard Matched".to_vec();
                    ctx.local.set_value(meta);
                    true
                }
                .boxed()
            }),
            Some(vec![mw_a, mw_b]), // 挂载两个中间件
        );

        // --- 3. 启动服务器 ---
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
        let actual_addr = listener.local_addr().unwrap();
        drop(listener);

        let server = Server::new(actual_addr, None);
        let server = server.http(hr).clone();

        tokio::spawn(async move {
            let _ = server.start().await;
        });

        // --- 4. 发起真实请求验证 ---
        let client = reqwest::Client::new();
        let mut res = None;

        // 尝试请求一个深层路径,验证通配符能否捕获
        for _ in 0..10 {
            sleep(Duration::from_millis(100)).await;
            if let Ok(r) = client
                .get(format!("http://{}/assets/css/main.css", actual_addr))
                .send()
                .await
            {
                res = Some(r);
                break;
            }
        }

        let response = res.expect("Server failed to respond");

        // --- 5. 断言验证 ---

        // 验证 1: 路径匹配
        assert_eq!(response.status().as_u16(), 200);
        assert_eq!(response.text().await.unwrap(), "Wildcard Matched");

        // 验证 2: 通配符命中计数
        assert_eq!(wildcard_hit_count.load(Ordering::SeqCst), 1);

        // 验证 3: 中间件执行顺序 (MW_A -> MW_B)
        let order = mw_exec_order.lock().unwrap();
        assert_eq!(*order, vec!["MW_A", "MW_B"]);
    }

    #[tokio::test]
    async fn test_middleware_interruption_full_stack() {
        // 验证中间件返回 false 时,处理器不应被执行
        let mut hr = Router::new(NodeType::Static("root".into()));
        let handler_executed = Arc::new(AtomicUsize::new(0));

        // 拦截中间件
        let mw_blocker: Arc<Executor> = Arc::new(|ctx: &mut Context| {
            async move {
                let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();
                meta.status = StatusCode::Forbidden; // 403
                meta.body = b"Blocked".to_vec();
                ctx.local.set_value(meta);
                false // 停止后续执行
            }
            .boxed()
        });

        let h_count = handler_executed.clone();
        hr.insert(
            "/admin",
            Some("GET"),
            Arc::new(move |_| {
                let c = h_count.clone();
                async move {
                    c.fetch_add(1, Ordering::SeqCst);
                    true
                }
                .boxed()
            }),
            Some(vec![mw_blocker]),
        );

        // 启动 Server (逻辑同上,略)
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();
        let server = HTTPServer::new(actual_addr, None);
        let server = server.http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        sleep(Duration::from_millis(200)).await;
        let res = reqwest::get(format!("http://{}/admin", actual_addr))
            .await
            .unwrap();

        // 断言验证
        assert_eq!(res.status().as_u16(), 403);
        let text = res.text().await.unwrap();
        assert!(text.contains("Blocked"));
        assert_eq!(handler_executed.load(Ordering::SeqCst), 0); // 处理器不应运行
    }

    #[tokio::test]
    async fn test_router_404_not_found() {
        let hr = Router::new(NodeType::Static("root".into())); // 空路由

        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();

        let server = Server::new(actual_addr, None);
        let server = server.http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        tokio::time::sleep(Duration::from_millis(200)).await;

        let res = reqwest::get(format!("http://{}/undefined/path", actual_addr))
            .await
            .unwrap();

        // 验证 handle_request 最后的 else 分支是否正确设置了 StatusCode::NotFound
        assert_eq!(res.status().as_u16(), 404);
    }
    // #[tokio::test]
    //     async fn test_form_body_auto_parsing() {
    //         let mut hr = Router::new(NodeType::Static("root".into()));

    //         hr.insert(
    //             "/submit",
    //             Some("POST"),
    //             Arc::new(|ctx: &mut Context<'_>| {
    //                 async move {
    //                     let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();

    //                     // 逻辑验证:从解析后的 Params 中提取
    //                     let user = meta.params.as_ref()
    //                         .and_then(|p| p.form.as_ref())
    //                         .and_then(|f| f.get("user"))
    //                         .cloned()
    //                         .unwrap_or_default();

    //                     meta.status = StatusCode::Ok;
    //                     meta.body = format!("User:{}", user.join("")).into_bytes();
    //                     ctx.local.set_value(meta);
    //                     true
    //                 }.boxed()
    //             }),
    //             None,
    //         );

    //         // --- 启动服务器 ---
    //         let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
    //         let actual_addr = tokio::net::TcpListener::bind(addr).await.unwrap().local_addr().unwrap();
    //         let mut server = HTTPServer::new(actual_addr, None);
    //         let server = server.http(hr);
    //         tokio::spawn(async move { let _ = server.start().await; });

    //         tokio::time::sleep(Duration::from_millis(200)).await;

    //         // --- 使用最基础的请求方式 ---
    //         let client = reqwest::Client::new();
    //         let body_str = "user=Gemini&age=20";

    //         let res = client
    //             .post(format!("http://{}/submit", actual_addr))
    //             // 显式设置这些 Header,触发你 handle_request 中的 if 条件
    //             .header("Content-Type", "application/x-www-form-urlencoded")
    //             .header("Content-Length", body_str.len().to_string())
    //             .body(body_str.to_string()) // 显式转为 String 以满足 RequestBuilder::body
    //             .send()
    //             .await
    //             .expect("Request failed");

    //         assert_eq!(res.status().as_u16(), 200);
    //         assert_eq!(res.text().await.unwrap(), "User:Gemini");
    //     }

    #[tokio::test]
    async fn test_router_404_fallback() {
        let hr = Router::new(NodeType::Static("root".into())); // 空路由

        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();
        let server = HTTPServer::new(actual_addr, None);
        let server = server.http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        tokio::time::sleep(Duration::from_millis(200)).await;

        let res = reqwest::get(format!("http://{}/not_exists", actual_addr))
            .await
            .unwrap();

        // 验证 handle_request 最后的 else 分支:设置了 404
        assert_eq!(res.status().as_u16(), 404);
    }

    #[tokio::test]
    async fn test_form_body_auto_parsing() {
        let mut hr = Router::new(NodeType::Static("root".into()));

        hr.insert(
            "/submit",
            Some("POST"),
            Arc::new(|ctx: &mut Context| {
                async move {
                    let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();

                    println!("meta.params = {:?}", meta.params);

                    // 验证 Params.form 是否被正确注入
                    let user = meta
                        .params
                        .as_ref()
                        .and_then(|p| p.form.as_ref())
                        .and_then(|f| f.get("user"))
                        .cloned()
                        .unwrap_or_default();

                    meta.status = StatusCode::Ok;
                    // 关键:必须设置 Body 响应,否则客户端会认为服务器没说完
                    meta.body = format!("User:{}", user.get(0).unwrap()).into_bytes();

                    println!("meta = {:?}", meta);

                    ctx.local.set_value(meta);
                    true
                }
                .boxed()
            }),
            None,
        );

        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();
        let server = HTTPServer::new(actual_addr, None);
        let server = server.http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        sleep(Duration::from_millis(200)).await;

        let client = reqwest::Client::new();
        let body_str = "user=Gemini&age=20";

        // 这里的请求必须完全匹配你 handle_request 里的条件
        let res = client
            .post(format!("http://{}/submit", actual_addr))
            .header("Content-Type", "application/x-www-form-urlencoded")
            // Content-Length 必须精确,否则 read_exact 会一直等待
            .header("Content-Length", body_str.len().to_string())
            .body(body_str)
            .send()
            .await
            .expect("Request failed");

        assert_eq!(res.status().as_u16(), 200);
        let text = res.text().await.unwrap();
        assert_eq!(text, "User:Gemini");
    }

    #[tokio::test]
    async fn test_wildcard_method_matching() {
        let mut hr = Router::new(NodeType::Static("root".into()));

        // 1. 注册一个通用处理器 (Method 为 None 或 "*")
        // 假设该处理器应处理除明确定义外的所有方法
        hr.insert(
            "/universal",
            None, // 内部会转为 "*"
            Arc::new(|ctx: &mut Context| {
                async move {
                    let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();
                    let method = meta.method.to_str().to_owned();

                    meta.status = StatusCode::Ok;
                    meta.body = format!("Method:{} handled by *", method).into_bytes();

                    // 记得更新 Content-Length 避免之前的 IncompleteBody 错误
                    let cl_key = HeaderKey::from_str("Content-Length").unwrap();
                    meta.headers.insert(cl_key, meta.body.len().to_string());

                    ctx.local.set_value(meta);
                    true
                }
                .boxed()
            }),
            None,
        );

        // --- 启动 Server ---
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();
        let server = HTTPServer::new(actual_addr, None);
        let server = server.http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        tokio::time::sleep(Duration::from_millis(200)).await;
        let client = reqwest::Client::new();

        // 验证 1: 发送 PUT 请求(未精确定义)
        let res_put = client
            .put(format!("http://{}/universal", actual_addr))
            .send()
            .await
            .unwrap();
        assert_eq!(res_put.status().as_u16(), 200);
        assert_eq!(res_put.text().await.unwrap(), "Method:PUT handled by *");

        // 验证 2: 发送 DELETE 请求
        let res_delete = client
            .delete(format!("http://{}/universal", actual_addr))
            .send()
            .await
            .unwrap();
        assert_eq!(
            res_delete.text().await.unwrap(),
            "Method:DELETE handled by *"
        );
    }

    #[tokio::test]
    async fn test_wildcard_method_middleware() {
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();

        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();

        let mut hr = Router::new(NodeType::Static("root".into()));
        let mw_hit_count = Arc::new(AtomicUsize::new(0));

        let mut server = HTTPServer::new(actual_addr, None);

        let count = mw_hit_count.clone();
        let mw_any: Arc<Executor> = Arc::new(move |_| {
            let c = count.clone();
            async move {
                c.fetch_add(1, Ordering::SeqCst);
                true
            }
            .boxed()
        });

        // 在通配符方法上插入中间件
        hr.insert(
            "/api",
            None,
            Arc::new(|_| async { true }.boxed()),
            Some(vec![mw_any]),
        );

        // ... 启动 Server ...

        let server = server.http(hr);
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;

        let client = reqwest::Client::new();

        // 分别发送 GET 和 POST
        // let _ = client
        //     .get(format!("http://{}/api", actual_addr))
        //     .send()
        //     .await;

        let res_get = client
            .get(format!("http://{}/api", actual_addr))
            .send()
            .await;

        match res_get {
            Ok(_) => println!("GET request sent successfully"),
            Err(e) => println!("GET request failed: {:?}", e),
        }
        let _ = client
            .post(format!("http://{}/api", actual_addr))
            .send()
            .await;

        // 验证中间件被执行了 2 次
        assert_eq!(mw_hit_count.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn test_wildcard_method_middleware_with_executor() {
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();

        let mut hr = Router::new(NodeType::Static("root".into()));
        let mw_hit_count = Arc::new(AtomicUsize::new(0));

        // 1. 使用原本的闭包方式定义的中间件
        let count = mw_hit_count.clone();
        let mw_counter = to_executor(move |_| {
            let c = count.clone();
            async move {
                c.fetch_add(1, Ordering::SeqCst);
                true
            }
            .boxed()
        });

        // 2. 使用 to_executor 定义一个额外的中间件(比如检查特定的 Header)
        let mw_header_check = to_executor(|_ctx| {
            async move {
                // 这里可以做一些逻辑判断
                println!("Middleware 2: Checking request...");
                true
            }
            .boxed()
        });

        // 将两个中间件都放入列表
        hr.insert(
            "/api",
            None, // 匹配所有方法 (*)
            Arc::new(|_| async { true }.boxed()),
            Some(vec![mw_counter, mw_header_check]), // 顺序执行
        );

        let server = HTTPServer::new(actual_addr, None).http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        // 给服务器起步时间,避免 Connection Refused
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        let client = reqwest::Client::new();

        // 分别发送 GET 和 POST
        let _ = client
            .get(format!("http://{}/api", actual_addr))
            .send()
            .await;
        let _ = client
            .post(format!("http://{}/api", actual_addr))
            .send()
            .await;

        // 每个请求命中了 1 个 method_key 为 * 的位置,里面有 2 个中间件
        // 总计增加应该是 2 (requests) * 1 (matching node) = 2
        // 注意:如果你在 handle_request 逻辑里循环执行了 vec 里的所有 mw,
        // 那么 c.fetch_add 还是会被调用两次。
        assert_eq!(mw_hit_count.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn test_full_macros_suite() {
        // 使用标准库锁简化测试代码中的同步操作

        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();

        let mut hr = Router::new(NodeType::Static("root".into()));
        // let trace = Arc::new(Mutex::new(Vec::<u8>::new()));

        // --- 1. 使用 exe! 定义带 Pre 处理的中间件 ---
        // let t1 = trace.clone();
        let mw_info = exe!(
            |ctx, info| {
                async move { true }.await;
                true
            },
            |_ctx| { "info".to_string() }
        );

        // --- 2. 使用 exe! 定义 Handler (修正版) ---
        let handler: Arc<Executor> = exe!(|ctx| {
            let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();
            meta.body = b"Macro OK".to_vec();
            ctx.local.set_value(meta);
            true
        });

        // --- 3. 使用 fluent API 注册 ---

        // 注册通配符方法路由到 /api/*
        hr.all("/api/all", handler.clone())
            .middleware(mw_info.clone())
            .register();

        // 注册特定 GET 路由
        hr.get("/api/specific", handler)
            .middleware(mw_info)
            .register();

        // --- 4. 启动服务器 ---
        let server = HTTPServer::new(actual_addr, None).http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;
        let client = reqwest::Client::new();

        // --- 5. 验证请求 ---

        // 测试 all! 宏 (POST 请求)
        let _ = client
            .post(format!("http://{}/api/all", actual_addr))
            .send()
            .await;

        // 测试 get! 宏
        let _ = client
            .get(format!("http://{}/api/specific", actual_addr))
            .send()
            .await;

        // --- 6. 断言结果 ---
        // let results = trace.lock().unwrap();
        // assert_eq!(results.len(), 2);
        // assert_eq!(results[0], "POST:/api/all");
        // assert_eq!(results[1], "GET:/api/specific");

        // println!("Macro Test Trace: {:?}", *results);
    }

    #[tokio::test]
    async fn test_full_macros_suite1() {
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();

        let mut hr = Router::new(NodeType::Static("root".into()));

        // --- 1. 中间件:演示 pre 块提取数据并存入 context ---
        let mw_info = exe!(
            |ctx, info| {
                // 将 pre 块提取的 info 放入 Response Header 传回 client
                let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();
                meta.headers
                    .insert(HeaderKey::from_str("X-Macro-Info").unwrap(), info);
                ctx.local.set_value(meta);

                async move { true }.await;
                true
            },
            |_ctx| {
                // pre 块:这里可以根据不同请求生成动态数据
                "processed-by-macro".to_string()
            }
        );

        // --- 2. Handler:修改 Body ---
        let handler: Arc<Executor> = exe!(|ctx| {
            let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();
            meta.body = b"Macro OK".to_vec();
            ctx.local.set_value(meta);
            true
        });

        // --- 3. 注册路由 ---
        hr.all("/api/all", handler.clone())
            .middleware(mw_info.clone())
            .register();
        hr.get("/api/specific", handler)
            .middleware(mw_info)
            .register();

        // --- 4. 启动服务器 ---
        let server = HTTPServer::new(actual_addr, None).http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;
        let client = reqwest::Client::new();

        // --- 5. 验证请求 ---

        // 验证 POST 到 all! 路由
        let resp_all = client
            .post(format!("http://{}/api/all", actual_addr))
            .send()
            .await
            .expect("POST request failed");

        // 检查 Header 是否含有中间件注入的信息
        assert_eq!(
            resp_all.headers().get("X-Macro-Info").unwrap(),
            "processed-by-macro"
        );
        // 检查 Body 是否由 Handler 正确设置
        assert_eq!(resp_all.text().await.unwrap(), "Macro OK");

        // 验证 GET 到 specific 路由
        let resp_get = client
            .get(format!("http://{}/api/specific", actual_addr))
            .send()
            .await
            .expect("GET request failed");

        assert_eq!(resp_get.status(), 200);
        assert_eq!(resp_get.text().await.unwrap(), "Macro OK");

        println!("Full macro suite test passed!");
    }

    #[tokio::test]
    async fn test_router_put_method() {
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();

        let mut hr = Router::new(NodeType::Static("root".into()));

        hr.put(
            "/data",
            Arc::new(|ctx: &mut Context| {
                async move {
                    let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();
                    meta.status = StatusCode::Ok;
                    meta.body = b"PUT OK".to_vec();
                    ctx.local.set_value(meta);
                    true
                }
                .boxed()
            }),
        )
        .register();

        let server = HTTPServer::new(actual_addr, None).http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        tokio::time::sleep(Duration::from_millis(200)).await;

        let client = reqwest::Client::new();
        let res = client
            .put(format!("http://{}/data", actual_addr))
            .send()
            .await
            .unwrap();

        assert_eq!(res.status().as_u16(), 200);
    }

    #[tokio::test]
    async fn test_router_delete_method() {
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();

        let mut hr = Router::new(NodeType::Static("root".into()));

        hr.delete(
            "/item/:id",
            Arc::new(|ctx: &mut Context| {
                async move {
                    let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();
                    meta.status = StatusCode::Ok;
                    meta.body = b"DELETED".to_vec();
                    ctx.local.set_value(meta);
                    true
                }
                .boxed()
            }),
        )
        .register();

        let server = HTTPServer::new(actual_addr, None).http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        tokio::time::sleep(Duration::from_millis(200)).await;

        let client = reqwest::Client::new();
        let res = client
            .delete(format!("http://{}/item/123", actual_addr))
            .send()
            .await
            .unwrap();

        assert_eq!(res.status().as_u16(), 200);
        assert_eq!(res.text().await.unwrap(), "DELETED");
    }

    #[tokio::test]
    async fn test_router_patch_method() {
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();

        let mut hr = Router::new(NodeType::Static("root".into()));

        hr.patch(
            "/update",
            Arc::new(|ctx: &mut Context| {
                async move {
                    let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();
                    meta.status = StatusCode::Ok;
                    meta.body = b"PATCHED".to_vec();
                    ctx.local.set_value(meta);
                    true
                }
                .boxed()
            }),
        )
        .register();

        let server = HTTPServer::new(actual_addr, None).http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        tokio::time::sleep(Duration::from_millis(200)).await;

        let client = reqwest::Client::new();
        let res = client
            .patch(format!("http://{}/update", actual_addr))
            .send()
            .await
            .unwrap();

        assert_eq!(res.status().as_u16(), 200);
    }

    #[tokio::test]
    async fn test_router_options_method() {
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();

        let mut hr = Router::new(NodeType::Static("root".into()));

        hr.options(
            "/api",
            Arc::new(|ctx: &mut Context| {
                async move {
                    let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();
                    meta.status = StatusCode::Ok;
                    meta.body = b"OPTIONS OK".to_vec();
                    ctx.local.set_value(meta);
                    true
                }
                .boxed()
            }),
        )
        .register();

        let server = HTTPServer::new(actual_addr, None).http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        tokio::time::sleep(Duration::from_millis(200)).await;

        let client = reqwest::Client::new();
        let res = client
            .request(
                reqwest::Method::OPTIONS,
                format!("http://{}/api", actual_addr),
            )
            .send()
            .await
            .unwrap();

        assert_eq!(res.status().as_u16(), 200);
    }

    #[tokio::test]
    async fn test_router_head_method() {
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let actual_addr = tokio::net::TcpListener::bind(addr)
            .await
            .unwrap()
            .local_addr()
            .unwrap();

        let mut hr = Router::new(NodeType::Static("root".into()));

        hr.head(
            "/head-test",
            Arc::new(|ctx: &mut Context| {
                async move {
                    let mut meta = ctx.local.get_value::<HttpMetadata>().unwrap();
                    meta.status = StatusCode::Ok;
                    ctx.local.set_value(meta);
                    true
                }
                .boxed()
            }),
        )
        .register();

        let server = HTTPServer::new(actual_addr, None).http(hr).clone();
        tokio::spawn(async move {
            let _ = server.start().await;
        });

        tokio::time::sleep(Duration::from_millis(200)).await;

        let client = reqwest::Client::new();
        let res = client
            .head(format!("http://{}/head-test", actual_addr))
            .send()
            .await
            .unwrap();

        assert_eq!(res.status().as_u16(), 200);
    }
}