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
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
mod utils;
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::{format_ident, quote, ToTokens};
use rand::Rng;
use serde_json::json;
use std::{collections::HashSet, sync::LazyLock};
use syn::Token;
use utils::StringExt as _;
/// CORS配置结构体(宏内部使用)
struct CorsAttrConfig {
origin: Option<String>,
methods: Option<String>,
headers: Option<String>,
max_age: Option<String>,
credentials: bool,
expose_headers: Option<String>,
}
/// 解析CORS属性
fn parse_cors_attr(tokens: &proc_macro2::TokenStream) -> CorsAttrConfig {
let config = CorsAttrConfig {
origin: None,
methods: None,
headers: None,
max_age: None,
credentials: false,
expose_headers: None,
};
if tokens.is_empty() {
return config; // 返回最小限制配置(origin="*", headers="*", methods自动计算)
}
// 解析 key = value 格式
use syn::parse::Parser;
fn parse_inner(input: syn::parse::ParseStream) -> syn::Result<CorsAttrConfig> {
let mut config = CorsAttrConfig {
origin: None,
methods: None,
headers: None,
max_age: None,
credentials: false,
expose_headers: None,
};
let vars =
syn::punctuated::Punctuated::<syn::MetaNameValue, Token![,]>::parse_terminated(input)?;
for meta in vars {
let key = meta
.path
.get_ident()
.map(|i| i.to_string())
.unwrap_or_default();
if let syn::Expr::Lit(expr_lit) = &meta.value {
match &expr_lit.lit {
syn::Lit::Str(s) => {
let val = s.value();
match key.as_str() {
"origin" => config.origin = Some(val),
"methods" => config.methods = Some(val),
"headers" => config.headers = Some(val),
"max_age" => config.max_age = Some(val),
"expose_headers" => config.expose_headers = Some(val),
_ => {}
}
}
syn::Lit::Bool(b) => {
if key == "credentials" {
config.credentials = b.value();
}
}
_ => {}
}
}
}
Ok(config)
}
match parse_inner.parse2(tokens.clone()) {
Ok(cfg) => cfg,
Err(e) => panic!("Failed to parse cors attributes: {e}"),
}
}
static ARG_TYPES: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
[
"String", "bool", "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize",
"f32", "f64",
]
.into_iter()
.collect()
});
/// Controller 字段类型
/// 验证 Controller 结构体字段
fn validate_controller_struct(item_struct: &syn::ItemStruct) -> (bool, bool) {
let mut has_once_cache = false;
let mut has_session_cache = false;
if let syn::Fields::Named(fields_named) = &item_struct.fields {
for field in &fields_named.named {
let field_type_str = field.ty.to_token_stream().to_string().type_simplify();
// 验证类型必须是 &OnceCache 或 &SessionCache(支持生命周期参数)
if field_type_str.contains("OnceCache") {
has_once_cache = true;
} else if field_type_str.contains("SessionCache") {
has_session_cache = true;
} else {
panic!(
"Controller field must be &OnceCache or &SessionCache, got: {}",
field_type_str
);
}
}
}
(has_once_cache, has_session_cache)
}
/// 解析 header 标注的 tokens,返回 (key, value)
fn parse_header_attr(tokens: &proc_macro2::TokenStream) -> Result<(String, String), syn::Error> {
use syn::parse::Parser;
let parser = |input: syn::parse::ParseStream| {
// 支持两种格式:
// 1. Key = "value" (标准 header)
// 2. Custom("key") = "value" (自定义 header)
let key_ident: Ident = input.parse()?;
let key_name = key_ident.to_string();
if key_name == "Custom" {
// Custom("key") = "value" 格式
let content;
syn::parenthesized!(content in input);
let key_lit: syn::LitStr = content.parse()?;
let key = key_lit.value();
let _: Token![=] = input.parse()?;
let value: syn::LitStr = input.parse()?;
Ok((key, value.value()))
} else {
// Key = "value" 格式
let _: Token![=] = input.parse()?;
let value: syn::LitStr = input.parse()?;
Ok((key_name, value.value()))
}
};
parser.parse2(tokens.clone())
}
fn random_ident() -> Ident {
let mut rng = rand::thread_rng();
let value = format!("__potato_id_{}", rng.r#gen::<u64>());
Ident::new(&value, Span::call_site())
}
fn attr_last_ident(attr: &syn::Attribute) -> Option<String> {
attr.meta
.path()
.segments
.iter()
.last()
.map(|segment| segment.ident.to_string())
}
fn parse_hook_attr_items(attr: &syn::Attribute, attr_name: &str) -> Vec<Ident> {
let parser = syn::punctuated::Punctuated::<Ident, syn::Token![,]>::parse_terminated;
let idents = attr.parse_args_with(parser).unwrap_or_else(|err| {
panic!("invalid `{attr_name}` annotation: {err}");
});
if idents.is_empty() {
panic!("`{attr_name}` annotation requires at least one function name");
}
idents.into_iter().collect()
}
fn collect_handler_hooks(root_fn: &mut syn::ItemFn) -> (Vec<Ident>, Vec<Ident>) {
enum HookKind {
Pre,
Post,
}
let mut hooks = vec![];
let mut new_attrs = Vec::with_capacity(root_fn.attrs.len());
for attr in root_fn.attrs.iter() {
match attr_last_ident(attr).as_deref() {
Some("preprocess") => {
hooks.extend(
parse_hook_attr_items(attr, "preprocess")
.into_iter()
.map(|item| (HookKind::Pre, item)),
);
}
Some("postprocess") => {
hooks.extend(
parse_hook_attr_items(attr, "postprocess")
.into_iter()
.map(|item| (HookKind::Post, item)),
);
}
_ => new_attrs.push(attr.clone()),
}
}
root_fn.attrs = new_attrs;
let mut preprocess_fns = vec![];
let mut postprocess_fns = vec![];
for (kind, hook) in hooks.into_iter() {
match kind {
HookKind::Pre => preprocess_fns.push(hook),
HookKind::Post => postprocess_fns.push(hook),
}
}
(preprocess_fns, postprocess_fns)
}
fn validate_preprocess_signature(root_fn: &syn::ItemFn) -> (String, bool, bool) {
if root_fn.sig.inputs.is_empty() || root_fn.sig.inputs.len() > 3 {
panic!("`preprocess` function must accept one to three arguments");
}
let mut arg_types = vec![];
for arg in root_fn.sig.inputs.iter() {
match arg {
syn::FnArg::Typed(arg) => {
arg_types.push(arg.ty.to_token_stream().to_string().type_simplify())
}
_ => panic!("`preprocess` function does not support receiver argument"),
}
}
if arg_types[0] != "& mut HttpRequest" {
panic!(
"`preprocess` first argument type must be `&mut potato::HttpRequest`, got `{}`",
arg_types[0]
);
}
let has_once_cache = arg_types.iter().any(|t| t == "& mut OnceCache");
let has_session_cache = arg_types.iter().any(|t| t == "& mut SessionCache");
if arg_types.len() == 2 && !has_once_cache && !has_session_cache {
panic!(
"`preprocess` second argument type must be `&mut potato::OnceCache` or `&mut potato::SessionCache`, got `{}`",
arg_types[1]
);
}
if arg_types.len() == 3 {
if !has_once_cache {
panic!("`preprocess` must have `&mut potato::OnceCache` as one of the arguments");
}
if !has_session_cache {
panic!("`preprocess` must have `&mut potato::SessionCache` as one of the arguments");
}
}
let ret_type = root_fn
.sig
.output
.to_token_stream()
.to_string()
.type_simplify();
match &ret_type[..] {
"Result<Option<HttpResponse>>" | "Option<HttpResponse>" | "Result<()>" | "()" => {}
_ => panic!(
"unsupported `preprocess` return type: `{ret_type}`, expected `anyhow::Result<Option<potato::HttpResponse>>`, `Option<potato::HttpResponse>`, `anyhow::Result<()>`, or `()`"
),
}
(ret_type, has_once_cache, has_session_cache)
}
fn validate_postprocess_signature(root_fn: &syn::ItemFn) -> (String, bool, bool) {
if root_fn.sig.inputs.len() < 2 && root_fn.sig.inputs.len() > 4 {
panic!("`postprocess` function must accept two to four arguments");
}
let mut arg_types = vec![];
for arg in root_fn.sig.inputs.iter() {
match arg {
syn::FnArg::Typed(arg) => {
arg_types.push(arg.ty.to_token_stream().to_string().type_simplify())
}
_ => panic!("`postprocess` function does not support receiver argument"),
}
}
if arg_types[0] != "& mut HttpRequest" {
panic!(
"`postprocess` first argument must be `&mut potato::HttpRequest`, got `{}`",
arg_types[0]
);
}
if arg_types[1] != "& mut HttpResponse" {
panic!(
"`postprocess` second argument must be `&mut potato::HttpResponse`, got `{}`",
arg_types[1]
);
}
let remaining_args = &arg_types[2..];
let has_once_cache = remaining_args.iter().any(|t| t == "& mut OnceCache");
let has_session_cache = remaining_args.iter().any(|t| t == "& mut SessionCache");
if arg_types.len() == 3 && !has_once_cache && !has_session_cache {
panic!(
"`postprocess` third argument must be `&mut potato::OnceCache` or `&mut potato::SessionCache`, got `{}`",
arg_types[2]
);
}
if arg_types.len() == 4 && (!has_once_cache || !has_session_cache) {
panic!(
"`postprocess` with 4 arguments must have both `&mut potato::OnceCache` and `&mut potato::SessionCache`"
);
}
let ret_type = root_fn
.sig
.output
.to_token_stream()
.to_string()
.type_simplify();
match &ret_type[..] {
"Result<()>" | "()" => {}
_ => panic!(
"unsupported `postprocess` return type: `{ret_type}`, expected `anyhow::Result<()>` or `()`"
),
}
(ret_type, has_once_cache, has_session_cache)
}
fn preprocess_macro(attr: TokenStream, input: TokenStream) -> TokenStream {
if !attr.is_empty() {
return input;
}
let root_fn = syn::parse_macro_input!(input as syn::ItemFn);
let fn_name = root_fn.sig.ident.clone();
let wrap_name = format_ident!("__potato_preprocess_adapter_{}", fn_name);
let wrap_name_inner = format_ident!("__potato_preprocess_adapter_inner_{}", fn_name);
let is_async = root_fn.sig.asyncness.is_some();
let (ret_type, has_once_cache, has_session_cache) = validate_preprocess_signature(&root_fn);
// 根据是否需要缓存生成不同的函数签名
let wrap_signature = match (has_once_cache, has_session_cache) {
(true, true) => quote! {
async fn #wrap_name_inner(
req: &mut potato::HttpRequest,
once_cache: &mut potato::OnceCache,
session_cache: &mut potato::SessionCache,
) -> anyhow::Result<Option<potato::HttpResponse>>
},
(true, false) => quote! {
async fn #wrap_name_inner(
req: &mut potato::HttpRequest,
once_cache: &mut potato::OnceCache,
) -> anyhow::Result<Option<potato::HttpResponse>>
},
(false, true) => quote! {
async fn #wrap_name_inner(
req: &mut potato::HttpRequest,
session_cache: &mut potato::SessionCache,
) -> anyhow::Result<Option<potato::HttpResponse>>
},
(false, false) => quote! {
async fn #wrap_name_inner(
req: &mut potato::HttpRequest,
) -> anyhow::Result<Option<potato::HttpResponse>>
},
};
// 根据实际使用情况调用函数
let call_body = if is_async {
match &ret_type[..] {
"Result<Option<HttpResponse>>" => match (has_once_cache, has_session_cache) {
(true, true) => {
quote! { #fn_name(req, once_cache, session_cache).await }
}
(true, false) => quote! { #fn_name(req, once_cache).await },
(false, true) => quote! { #fn_name(req, session_cache).await },
(false, false) => quote! { #fn_name(req).await },
},
"Option<HttpResponse>" => match (has_once_cache, has_session_cache) {
(true, true) => quote! { Ok(#fn_name(req, once_cache, session_cache).await) },
(true, false) => quote! { Ok(#fn_name(req, once_cache).await) },
(false, true) => quote! { Ok(#fn_name(req, session_cache).await) },
(false, false) => quote! { Ok(#fn_name(req).await) },
},
"Result<()>" => match (has_once_cache, has_session_cache) {
(true, true) => {
quote! { #fn_name(req, once_cache, session_cache).await.map(|_| None) }
}
(true, false) => quote! { #fn_name(req, once_cache).await.map(|_| None) },
(false, true) => quote! { #fn_name(req, session_cache).await.map(|_| None) },
(false, false) => quote! { #fn_name(req).await.map(|_| None) },
},
"()" => match (has_once_cache, has_session_cache) {
(true, true) => quote! { #fn_name(req, once_cache, session_cache).await; Ok(None) },
(true, false) => quote! { #fn_name(req, once_cache).await; Ok(None) },
(false, true) => quote! { #fn_name(req, session_cache).await; Ok(None) },
(false, false) => quote! { #fn_name(req).await; Ok(None) },
},
_ => unreachable!(),
}
} else {
match &ret_type[..] {
"Result<Option<HttpResponse>>" => match (has_once_cache, has_session_cache) {
(true, true) => quote! { #fn_name(req, once_cache, session_cache) },
(true, false) => quote! { #fn_name(req, once_cache) },
(false, true) => quote! { #fn_name(req, session_cache) },
(false, false) => quote! { #fn_name(req) },
},
"Option<HttpResponse>" => match (has_once_cache, has_session_cache) {
(true, true) => quote! { Ok(#fn_name(req, once_cache, session_cache)) },
(true, false) => quote! { Ok(#fn_name(req, once_cache)) },
(false, true) => quote! { Ok(#fn_name(req, session_cache)) },
(false, false) => quote! { Ok(#fn_name(req)) },
},
"Result<()>" => match (has_once_cache, has_session_cache) {
(true, true) => quote! { #fn_name(req, once_cache, session_cache).map(|_| None) },
(true, false) => quote! { #fn_name(req, once_cache).map(|_| None) },
(false, true) => quote! { #fn_name(req, session_cache).map(|_| None) },
(false, false) => quote! { #fn_name(req).map(|_| None) },
},
"()" => match (has_once_cache, has_session_cache) {
(true, true) => quote! { #fn_name(req, once_cache, session_cache); Ok(None) },
(true, false) => quote! { #fn_name(req, once_cache); Ok(None) },
(false, true) => quote! { #fn_name(req, session_cache); Ok(None) },
(false, false) => quote! { #fn_name(req); Ok(None) },
},
_ => unreachable!(),
}
};
// 生成wrapper函数,根据cache需求调用inner函数
let wrapper_body = match (has_once_cache, has_session_cache) {
(true, true) => quote! {
#wrap_name_inner(
req,
once_cache.expect("OnceCache required but not provided"),
session_cache.expect("SessionCache required but not provided"),
).await
},
(true, false) => quote! {
#wrap_name_inner(
req,
once_cache.expect("OnceCache required but not provided"),
).await
},
(false, true) => quote! {
#wrap_name_inner(
req,
session_cache.expect("SessionCache required but not provided"),
).await
},
(false, false) => quote! {
#wrap_name_inner(req).await
},
};
quote! {
#root_fn
#[doc(hidden)]
#wrap_signature {
#call_body
}
#[doc(hidden)]
pub async fn #wrap_name(
req: &mut potato::HttpRequest,
once_cache: Option<&mut potato::OnceCache>,
session_cache: Option<&mut potato::SessionCache>,
) -> anyhow::Result<Option<potato::HttpResponse>> {
#wrapper_body
}
}
.into()
}
fn postprocess_macro(attr: TokenStream, input: TokenStream) -> TokenStream {
if !attr.is_empty() {
return input;
}
let root_fn = syn::parse_macro_input!(input as syn::ItemFn);
let fn_name = root_fn.sig.ident.clone();
let wrap_name = format_ident!("__potato_postprocess_adapter_{}", fn_name);
let wrap_name_inner = format_ident!("__potato_postprocess_adapter_inner_{}", fn_name);
let is_async = root_fn.sig.asyncness.is_some();
let (ret_type, has_once_cache, has_session_cache) = validate_postprocess_signature(&root_fn);
// 根据是否需要缓存生成不同的函数签名
let wrap_signature = match (has_once_cache, has_session_cache) {
(true, true) => quote! {
async fn #wrap_name_inner(
req: &mut potato::HttpRequest,
res: &mut potato::HttpResponse,
once_cache: &mut potato::OnceCache,
session_cache: &mut potato::SessionCache,
) -> anyhow::Result<()>
},
(true, false) => quote! {
async fn #wrap_name_inner(
req: &mut potato::HttpRequest,
res: &mut potato::HttpResponse,
once_cache: &mut potato::OnceCache,
) -> anyhow::Result<()>
},
(false, true) => quote! {
async fn #wrap_name_inner(
req: &mut potato::HttpRequest,
res: &mut potato::HttpResponse,
session_cache: &mut potato::SessionCache,
) -> anyhow::Result<()>
},
(false, false) => quote! {
async fn #wrap_name_inner(
req: &mut potato::HttpRequest,
res: &mut potato::HttpResponse,
) -> anyhow::Result<()>
},
};
// 根据实际使用情况调用函数
let call_body = if is_async {
match &ret_type[..] {
"Result<()>" => {
if has_once_cache && has_session_cache {
quote! {
#fn_name(req, res, once_cache, session_cache).await
}
} else if has_once_cache {
quote! {
#fn_name(req, res, once_cache).await
}
} else if has_session_cache {
quote! {
#fn_name(req, res, session_cache).await
}
} else {
quote! {
#fn_name(req, res).await
}
}
}
"()" => {
if has_once_cache && has_session_cache {
quote! {
#fn_name(req, res, once_cache, session_cache).await;
Ok(())
}
} else if has_once_cache {
quote! {
#fn_name(req, res, once_cache).await;
Ok(())
}
} else if has_session_cache {
quote! {
#fn_name(req, res, session_cache).await;
Ok(())
}
} else {
quote! {
#fn_name(req, res).await;
Ok(())
}
}
}
_ => unreachable!(),
}
} else {
match &ret_type[..] {
"Result<()>" => {
if has_once_cache && has_session_cache {
quote! {
#fn_name(req, res, once_cache, session_cache)
}
} else if has_once_cache {
quote! {
#fn_name(req, res, once_cache)
}
} else if has_session_cache {
quote! {
#fn_name(req, res, session_cache)
}
} else {
quote! {
#fn_name(req, res)
}
}
}
"()" => {
if has_once_cache && has_session_cache {
quote! {
#fn_name(req, res, once_cache, session_cache);
Ok(())
}
} else if has_once_cache {
quote! {
#fn_name(req, res, once_cache);
Ok(())
}
} else if has_session_cache {
quote! {
#fn_name(req, res, session_cache);
Ok(())
}
} else {
quote! {
#fn_name(req, res);
Ok(())
}
}
}
_ => unreachable!(),
}
};
// 生成wrapper函数,根据cache需求调用inner函数
let wrapper_body = match (has_once_cache, has_session_cache) {
(true, true) => quote! {
#wrap_name_inner(
req,
res,
once_cache.expect("OnceCache required but not provided"),
session_cache.expect("SessionCache required but not provided"),
).await
},
(true, false) => quote! {
#wrap_name_inner(
req,
res,
once_cache.expect("OnceCache required but not provided"),
).await
},
(false, true) => quote! {
#wrap_name_inner(
req,
res,
session_cache.expect("SessionCache required but not provided"),
).await
},
(false, false) => quote! {
#wrap_name_inner(req, res).await
},
};
quote! {
#root_fn
#[doc(hidden)]
#wrap_signature {
#call_body
}
#[doc(hidden)]
pub async fn #wrap_name(
req: &mut potato::HttpRequest,
res: &mut potato::HttpResponse,
once_cache: Option<&mut potato::OnceCache>,
session_cache: Option<&mut potato::SessionCache>,
) -> anyhow::Result<()> {
#wrapper_body
}
}
.into()
}
fn http_handler_macro(attr: TokenStream, input: TokenStream, req_name: &str) -> TokenStream {
let req_name = Ident::new(req_name, Span::call_site());
// 解析函数,检查是否有 receiver(&self / &mut self)
let root_fn_for_check = syn::parse::<syn::ItemFn>(input.clone());
let has_receiver = if let Ok(ref func) = root_fn_for_check {
func.sig
.inputs
.iter()
.any(|arg| matches!(arg, syn::FnArg::Receiver(_)))
} else {
false
};
let (route_path, default_headers) = {
let mut oroute_path = syn::parse::<syn::LitStr>(attr.clone())
.ok()
.map(|path| path.value());
let mut default_headers: Vec<(String, String)> = Vec::new();
//
if oroute_path.is_none() {
let http_parser = syn::meta::parser(|meta| {
if meta.path.is_ident("path") {
if let Ok(arg) = meta.value() {
if let Ok(route_path) = arg.parse::<syn::LitStr>() {
let route_path = route_path.value();
oroute_path = Some(route_path);
}
}
Ok(())
} else if meta.path.is_ident("header") {
// 解析 header(key = value) 格式
let content;
syn::parenthesized!(content in meta.input);
let key: Ident = content.parse()?;
let _: syn::Token![=] = content.parse()?;
let value: syn::LitStr = content.parse()?;
default_headers.push((key.to_string(), value.value()));
Ok(())
} else {
Err(meta.error("unsupported annotation property"))
}
});
syn::parse_macro_input!(attr with http_parser);
}
// 如果没有提供 path 且有 receiver,可能是 controller 方法
if oroute_path.is_none() && has_receiver {
// 这将在后续代码中处理,先设置为空
} else if oroute_path.is_none() {
panic!("`path` argument is required for non-controller methods");
}
let route_path = oroute_path.unwrap_or_default();
// 如果是 controller 方法,需要处理路径拼接
let route_path = if has_receiver {
if route_path.is_empty() {
// 没有指定 path,使用 controller base path(稍后在生成的代码中读取常量)
String::new()
} else {
// 指定了 path,需要拼接到 controller base path
// 这里先标记,稍后在生成的代码中处理
route_path
}
} else {
if route_path.is_empty() {
panic!("`path` argument is required for non-controller methods");
}
route_path
};
if !route_path.is_empty() && !route_path.starts_with('/') {
panic!("route path must start with '/'");
}
(route_path, default_headers)
};
// 解析函数上的 #[potato::header(...)] 标注
let mut root_fn = syn::parse_macro_input!(input as syn::ItemFn);
let mut fn_headers: Vec<(String, String)> = Vec::new();
let mut cors_config: Option<CorsAttrConfig> = None;
let mut max_concurrency: Option<usize> = None;
let mut remaining_attrs = Vec::new();
for attr in root_fn.attrs.iter() {
// 检查是否是 header 标注(支持 #[header(...)] 和 #[potato::header(...)] 两种形式)
let is_header_attr = attr.path().is_ident("header")
|| (attr.path().segments.len() == 2
&& attr
.path()
.segments
.iter()
.next()
.map(|s| s.ident.to_string())
== Some("potato".to_string())
&& attr
.path()
.segments
.iter()
.last()
.map(|s| s.ident.to_string())
== Some("header".to_string()));
if is_header_attr {
if let syn::Meta::List(meta_list) = &attr.meta {
// 解析 header(Cache_Control = "no-store, no-cache, max-age=0") 或 header(Custom("key") = "value")
if let Ok((key, value)) = parse_header_attr(&meta_list.tokens) {
fn_headers.push((key, value));
}
}
continue;
}
// 检查是否是 cors 标注
let is_cors_attr = attr.path().is_ident("cors")
|| (attr.path().segments.len() == 2
&& attr
.path()
.segments
.iter()
.next()
.map(|s| s.ident.to_string())
== Some("potato".to_string())
&& attr
.path()
.segments
.iter()
.last()
.map(|s| s.ident.to_string())
== Some("cors".to_string()));
if is_cors_attr {
if let syn::Meta::List(meta_list) = &attr.meta {
cors_config = Some(parse_cors_attr(&meta_list.tokens));
} else {
// 无参数时使用最小限制配置
cors_config = Some(CorsAttrConfig {
origin: None,
methods: None,
headers: None,
max_age: None,
credentials: false,
expose_headers: None,
});
}
continue;
}
// 检查是否是 max_concurrency 标注
let is_max_concurrency_attr = attr.path().is_ident("max_concurrency")
|| (attr.path().segments.len() == 2
&& attr
.path()
.segments
.iter()
.next()
.map(|s| s.ident.to_string())
== Some("potato".to_string())
&& attr
.path()
.segments
.iter()
.last()
.map(|s| s.ident.to_string())
== Some("max_concurrency".to_string()));
if is_max_concurrency_attr {
if let syn::Meta::List(meta_list) = &attr.meta {
let tokens = &meta_list.tokens;
// 直接解析为数字
if let Ok(lit_int) = syn::parse2::<syn::LitInt>(tokens.clone()) {
if let Ok(val) = lit_int.base10_parse::<usize>() {
if val == 0 {
panic!("max_concurrency must be greater than 0");
}
max_concurrency = Some(val);
} else {
panic!("invalid max_concurrency value");
}
} else {
panic!(
"max_concurrency requires a numeric value, e.g., #[max_concurrency(10)]"
);
}
} else if let syn::Meta::NameValue(name_value) = &attr.meta {
if let syn::Expr::Lit(expr_lit) = &name_value.value {
if let syn::Lit::Int(lit_int) = &expr_lit.lit {
if let Ok(val) = lit_int.base10_parse::<usize>() {
if val == 0 {
panic!("max_concurrency must be greater than 0");
}
max_concurrency = Some(val);
} else {
panic!("invalid max_concurrency value");
}
} else {
panic!("max_concurrency requires a numeric value");
}
} else {
panic!("max_concurrency requires a numeric value");
}
} else {
panic!("max_concurrency requires a numeric value, e.g., #[max_concurrency(10)]");
}
continue;
}
remaining_attrs.push(attr.clone());
}
// 合并默认headers和函数headers
let mut all_headers = default_headers;
all_headers.extend(fn_headers);
root_fn.attrs = remaining_attrs;
let (preprocess_fns, postprocess_fns) = collect_handler_hooks(&mut root_fn);
// 检测handler自身是否需要缓存
let handler_has_once_cache = root_fn.sig.inputs.iter().any(|arg| {
if let syn::FnArg::Typed(arg) = arg {
arg.ty.to_token_stream().to_string().type_simplify() == "& mut OnceCache"
} else {
false
}
});
let handler_has_session_cache = root_fn.sig.inputs.iter().any(|arg| {
if let syn::FnArg::Typed(arg) = arg {
arg.ty.to_token_stream().to_string().type_simplify() == "& mut SessionCache"
} else {
false
}
});
// 修复:只有当 handler 本身需要缓存时,才设置 need_session_cache 和 need_once_cache
// preprocess/postprocess 钩子如果需要缓存,它们可以通过参数声明
// 但如果 handler 不需要缓存,我们不应该强制要求 Authorization header
// 这样可以避免给不需要认证的 handler 添加不必要的认证要求
let need_once_cache = handler_has_once_cache;
let need_session_cache = handler_has_session_cache;
let preprocess_adapters: Vec<Ident> = preprocess_fns
.iter()
.map(|name| format_ident!("__potato_preprocess_adapter_{}", name))
.collect();
let postprocess_adapters: Vec<Ident> = postprocess_fns
.iter()
.map(|name| format_ident!("__potato_postprocess_adapter_{}", name))
.collect();
let doc_show = {
let mut doc_show = true;
for attr in root_fn.attrs.iter() {
if attr.meta.path().get_ident().map(|p| p.to_string()) == Some("doc".to_string()) {
if let Ok(meta_list) = attr.meta.require_list() {
if meta_list.tokens.to_string() == "hidden" {
doc_show = false;
break;
}
}
}
}
doc_show
};
let doc_auth = need_session_cache;
let doc_summary = {
let mut docs = vec![];
for attr in root_fn.attrs.iter() {
if let Ok(attr) = attr.meta.require_name_value() {
if attr.path.get_ident().map(|p| p.to_string()) == Some("doc".to_string()) {
let mut doc = attr.value.to_token_stream().to_string();
if doc.starts_with('\"') {
doc.remove(0);
doc.pop();
}
docs.push(doc);
}
}
}
if docs.iter().all(|d| d.starts_with(' ')) {
for doc in docs.iter_mut() {
doc.remove(0);
}
}
docs.join("\n")
};
let doc_desp = "";
let fn_name = root_fn.sig.ident.clone();
let is_async = root_fn.sig.asyncness.is_some();
// 检测是否有 receiver(&self / &mut self)- controller 方法
let has_receiver = root_fn
.sig
.inputs
.iter()
.any(|arg| matches!(arg, syn::FnArg::Receiver(_)));
// 生成最终路径(如果是 controller 方法,需要拼接)
// 注意:由于路由注册需要编译期常量,路径拼接必须在宏展开时完成
// 但 controller 宏和 http_get 宏是独立展开的,无法直接共享信息
// 因此这里采用简化方案:直接使用 route_path,路径拼接由用户保证正确
let final_path = if has_receiver {
// Controller 方法:如果 route_path 为空,说明用户希望使用 controller 的 base path
// 但这里无法获取 base path,所以要求用户必须指定完整路径或相对路径
if route_path.is_empty() {
// 暂时使用一个占位符,实际应该在 controller 宏中处理
// 这里我们先要求用户必须提供路径
panic!("Controller methods must specify a path (e.g., #[potato::http_get(\"/\")])");
} else {
route_path
}
} else {
if route_path.is_empty() {
panic!("`path` argument is required for non-controller methods");
}
route_path
};
let final_path_expr = quote! { #final_path };
// 生成 tag 表达式
let tag_expr = if has_receiver {
quote! { __POTATO_CONTROLLER_NAME }
} else {
quote! { "" }
};
let wrap_func_name = random_ident();
let mut args = vec![];
let mut arg_names = vec![];
let mut arg_types = vec![];
let mut doc_args = vec![];
for arg in root_fn.sig.inputs.iter() {
// 支持 receiver 参数(&self / &mut self)- controller 方法
if let syn::FnArg::Receiver(_receiver) = arg {
// 跳过 receiver,不生成参数绑定代码
// controller 实例将在包装函数中创建
continue;
}
if let syn::FnArg::Typed(arg) = arg {
let arg_type_str = arg
.ty
.as_ref()
.to_token_stream()
.to_string()
.type_simplify();
let arg_name_str = arg.pat.to_token_stream().to_string();
let arg_value = match &arg_type_str[..] {
"& mut HttpRequest" => quote! { req },
"& mut OnceCache" => {
quote! { __potato_once_cache.as_mut().expect("OnceCache not available") }
}
"& mut SessionCache" => {
quote! { __potato_session_cache.as_mut().expect("SessionCache not available") }
}
"PostFile" => {
doc_args.push(json!({ "name": arg_name_str, "type": arg_type_str }));
quote! {
match req.body_files.get(&potato::utils::refstr::LocalHipStr<'static>::from_str(#arg_name_str)).cloned() {
Some(file) => file,
None => return potato::HttpResponse::error(format!("miss arg: {}", #arg_name_str)),
}
}
}
arg_type_str if ARG_TYPES.contains(arg_type_str) => {
doc_args.push(json!({ "name": arg_name_str, "type": arg_type_str }));
let mut arg_value = quote! {
match req.body_pairs
.get(&potato::hipstr::LocalHipStr::from(#arg_name_str))
.map(|p| p.to_string()) {
Some(val) => val,
None => match req.url_query
.get(&potato::hipstr::LocalHipStr::from(#arg_name_str))
.map(|p| p.as_str().to_string()) {
Some(val) => val,
None => return potato::HttpResponse::error(format!("miss arg: {}", #arg_name_str)),
},
}
};
if arg_type_str != "String" {
arg_value = quote! {
match #arg_value.parse() {
Ok(val) => val,
Err(err) => return potato::HttpResponse::error(format!("arg[{}] is not {} type", #arg_name_str, #arg_type_str)),
}
}
}
arg_value
}
_ => panic!("unsupported arg type: [{arg_type_str}]"),
};
args.push(arg_value);
arg_names.push(random_ident());
// 保存参数类型信息,用于后续生成 call_expr
arg_types.push(arg_type_str);
}
}
let wrap_func_name2 = random_ident();
let ret_type = root_fn
.sig
.output
.to_token_stream()
.to_string()
.type_simplify();
// 如果有 receiver,需要生成 __potato_create_controller 函数
// 通过检查是否存在 controller 常量来判断
let _controller_create_fn = if has_receiver {
quote! {
// 这个函数应该由 controller 宏生成,这里只是引用
// 如果编译出错,说明没有正确使用 #[potato::controller]
}
} else {
quote! {}
};
// 为每个参数生成调用代码
let call_args: Vec<_> = args
.iter()
.enumerate()
.map(|(i, _arg)| {
let arg_name = &arg_names[i];
let arg_type = &arg_types[i];
// 对于 HttpRequest,直接使用 req,不要通过中间变量
if arg_type == "& mut HttpRequest" {
quote! { req }
} else {
quote! { #arg_name }
}
})
.collect();
let call_expr = if has_receiver {
// Controller 方法:直接调用方法(暂不支持字段注入)
// 注意:当前版本不支持 controller 字段,方法应该是静态方法
// 如果要支持字段,需要在包装函数中实例化 controller
match args.len() {
0 => quote! { #fn_name() },
1 => {
let arg_name = &arg_names[0];
let arg = &args[0];
let arg_type = &arg_types[0];
if arg_type == "& mut HttpRequest" {
quote! { #fn_name(req) }
} else {
quote! {{
let #arg_name = #arg;
#fn_name(#arg_name)
}}
}
}
_ => {
let let_bindings: Vec<_> = arg_types
.iter()
.zip(arg_names.iter())
.zip(args.iter())
.filter(|((arg_type, _), _)| *arg_type != "& mut HttpRequest")
.map(|((_, arg_name), arg)| quote! { let #arg_name = #arg; })
.collect();
quote! {{
#(#let_bindings)*
#fn_name(#(#call_args),*)
}}
}
}
} else {
// 普通方法:直接调用函数
match args.len() {
0 => quote! { #fn_name() },
1 => {
let arg_name = &arg_names[0];
let arg = &args[0];
let arg_type = &arg_types[0];
// 检查是否是 HttpRequest 类型
if arg_type == "& mut HttpRequest" {
quote! { #fn_name(req) }
} else {
quote! {{
let #arg_name = #arg;
#fn_name(#arg_name)
}}
}
}
_ => {
// 只为非 HttpRequest 类型的参数创建中间变量
let let_bindings: Vec<_> = arg_types
.iter()
.zip(arg_names.iter())
.zip(args.iter())
.filter(|((arg_type, _), _)| *arg_type != "& mut HttpRequest")
.map(|((_, arg_name), arg)| quote! { let #arg_name = #arg; })
.collect();
quote! {{
#(#let_bindings)*
#fn_name(#(#call_args),*)
}}
}
}
};
let handler_wrap_func_body = if is_async {
match &ret_type[..] {
"Result<()>" => quote! {
match #call_expr.await {
Ok(_) => Ok(potato::HttpResponse::text("ok")),
Err(err) => Err(err),
}
},
"Result<HttpResponse>" | "anyhow::Result<HttpResponse>" => quote! {
match #call_expr.await {
Ok(ret) => Ok(ret),
Err(err) => Err(err),
}
},
"Result<String>" | "anyhow::Result<String>" => quote! {
match #call_expr.await {
Ok(ret) => Ok(potato::HttpResponse::html(ret)),
Err(err) => Err(err),
}
},
"Result<& 'static str>" | "anyhow::Result<& 'static str>" => quote! {
match #call_expr.await {
Ok(ret) => Ok(potato::HttpResponse::html(ret)),
Err(err) => Err(err),
}
},
"()" => quote! {
#call_expr.await;
Ok(potato::HttpResponse::text("ok"))
},
"HttpResponse" => quote! {
Ok(#call_expr.await)
},
"String" => quote! {
Ok(potato::HttpResponse::html(#call_expr.await))
},
"& 'static str" => quote! {
Ok(potato::HttpResponse::html(#call_expr.await))
},
_ => panic!("unsupported ret type: {ret_type}"),
}
} else {
match &ret_type[..] {
"Result<()>" => quote! {
match #call_expr {
Ok(_) => Ok(potato::HttpResponse::text("ok")),
Err(err) => Err(err),
}
},
"Result<HttpResponse>" | "anyhow::Result<HttpResponse>" => quote! {
match #call_expr {
Ok(ret) => Ok(ret),
Err(err) => Err(err),
}
},
"Result<String>" | "anyhow::Result<String>" => quote! {
match #call_expr {
Ok(ret) => Ok(potato::HttpResponse::html(ret)),
Err(err) => Err(err),
}
},
"Result<& 'static str>" | "anyhow::Result<& 'static str>" => quote! {
match #call_expr {
Ok(ret) => Ok(potato::HttpResponse::html(ret)),
Err(err) => Err(err),
}
},
"()" => quote! {
#call_expr;
Ok(potato::HttpResponse::text("ok"))
},
"HttpResponse" => quote! {
Ok(#call_expr)
},
"String" => quote! {
Ok(potato::HttpResponse::html(#call_expr))
},
"& 'static str" => quote! {
Ok(potato::HttpResponse::html(#call_expr))
},
_ => panic!("unsupported ret type: {ret_type}"),
}
};
let doc_args = serde_json::to_string(&doc_args).unwrap();
// 生成添加headers的代码
let add_headers_code = if all_headers.is_empty() {
quote! {}
} else {
let header_statements = all_headers.iter().map(|(key, value)| {
// 将下划线转换为HTTP标准命名 (例如 Cache_Control -> Cache-Control)
let http_key = key.replace("_", "-");
quote! {
__potato_response.add_header(
std::borrow::Cow::Borrowed(#http_key),
std::borrow::Cow::Borrowed(#value)
);
}
});
quote! {
#(#header_statements)*
}
};
// 如果存在CORS配置,生成CORS headers注入代码
let cors_headers_code = if let Some(cors) = &cors_config {
let mut statements = vec![];
// origin: 默认"*"
let origin_val = cors.origin.as_deref().unwrap_or("*");
statements.push(quote! {
__potato_response.add_header(
"Access-Control-Allow-Origin".into(),
#origin_val.into()
);
});
// methods: 仅在用户指定时添加,否则由OPTIONS请求自动计算
if let Some(ref methods) = cors.methods {
let mut methods_list: Vec<&str> = methods.split(',').map(|s| s.trim()).collect();
if !methods_list.contains(&"HEAD") {
methods_list.push("HEAD");
}
if !methods_list.contains(&"OPTIONS") {
methods_list.push("OPTIONS");
}
let methods_str = methods_list.join(",");
statements.push(quote! {
__potato_response.add_header(
"Access-Control-Allow-Methods".into(),
#methods_str.into()
);
});
}
// headers: 默认"*"
let headers_val = cors.headers.as_deref().unwrap_or("*");
statements.push(quote! {
__potato_response.add_header(
"Access-Control-Allow-Headers".into(),
#headers_val.into()
);
});
// max_age: 默认"86400"
if let Some(ref max_age) = cors.max_age {
statements.push(quote! {
__potato_response.add_header(
"Access-Control-Max-Age".into(),
#max_age.into()
);
});
} else {
statements.push(quote! {
__potato_response.add_header(
"Access-Control-Max-Age".into(),
"86400".into()
);
});
}
if cors.credentials {
statements.push(quote! {
__potato_response.add_header(
"Access-Control-Allow-Credentials".into(),
"true".into()
);
});
}
if let Some(ref expose_headers) = cors.expose_headers {
statements.push(quote! {
__potato_response.add_header(
"Access-Control-Expose-Headers".into(),
#expose_headers.into()
);
});
}
quote! { #(#statements)* }
} else {
quote! {}
};
// 如果存在CORS配置且是PUT/POST/DELETE,自动生成HEAD handler
let auto_head_handler = if cors_config.is_some()
&& (req_name == "POST" || req_name == "PUT" || req_name == "DELETE")
{
let head_wrap_name = format_ident!("__potato_cors_head_{}", fn_name);
Some(quote! {
#[doc(hidden)]
fn #head_wrap_name(req: &mut potato::HttpRequest) -> potato::HttpResponse {
// HEAD请求直接返回空响应,不执行原handler
// CORS headers会通过postprocess机制自动添加
potato::HttpResponse::html("")
}
})
} else {
None
};
// 如果指定了max_concurrency,生成静态信号量
let semaphore_static = if let Some(max_conn) = max_concurrency {
let semaphore_name =
format_ident!("__POTATO_SEMAPHORE_{}", fn_name.to_string().to_uppercase());
Some(quote! {
#[doc(hidden)]
#[allow(non_upper_case_globals)]
static #semaphore_name: std::sync::LazyLock<tokio::sync::Semaphore> =
std::sync::LazyLock::new(|| tokio::sync::Semaphore::new(#max_conn));
})
} else {
None
};
let wrap_func_body = if is_async {
if max_concurrency.is_some() {
let semaphore_name =
format_ident!("__POTATO_SEMAPHORE_{}", fn_name.to_string().to_uppercase());
quote! {
let __potato_permit = #semaphore_name.acquire().await;
// 获取自定义错误处理器
let __potato_error_handler: Option<potato::ErrorHandler> = {
let mut handler = None;
for flag in potato::inventory::iter::<potato::ErrorHandlerFlag> {
handler = Some(flag.handler.clone());
break;
}
handler
};
// 按需创建缓存对象
let mut __potato_once_cache: Option<potato::OnceCache> = if #need_once_cache {
Some(potato::OnceCache::new())
} else {
None
};
let mut __potato_session_cache: Option<potato::SessionCache> = if #need_session_cache {
// 从 Authorization header 中提取 Bearer token 并加载 session
if let Some(h) = req.headers.get(&potato::utils::refstr::HeaderOrHipStr::from_str("Authorization")) {
let header_value = h.as_str();
if header_value.starts_with("Bearer ") {
potato::SessionCache::from_token(&header_value[7..]).await.ok()
} else {
None
}
} else {
None
}
} else {
None
};
// 如果 handler 需要 SessionCache 但没有提供 Authorization header,返回 401
if #need_session_cache && __potato_session_cache.is_none() {
let mut __potato_resp = potato::HttpResponse::text("Unauthorized: Missing or invalid Authorization header");
__potato_resp.http_code = 401;
return __potato_resp;
}
// 自动解析请求中的Cookie
if let Some(ref mut session_cache) = __potato_session_cache {
if let Some(cookie_header) = req.headers.get(&potato::utils::refstr::HeaderOrHipStr::from_str("Cookie")) {
session_cache.parse_request_cookies(cookie_header.as_str());
}
}
let mut __potato_pre_response: Option<potato::HttpResponse> = None;
#(
if __potato_pre_response.is_none() {
__potato_pre_response = match #preprocess_adapters(
req,
__potato_once_cache.as_mut(),
__potato_session_cache.as_mut(),
).await {
Ok(Some(ret)) => Some(ret),
Ok(None) => None,
Err(err) => {
let handler = &__potato_error_handler;
Some(match handler {
Some(potato::ErrorHandler::Async(h)) => h(req, err).await,
Some(potato::ErrorHandler::Sync(h)) => h(req, err),
None => potato::HttpResponse::error(format!("{err:?}")),
})
}
};
}
)*
let mut __potato_response = match __potato_pre_response {
Some(ret) => ret,
None => match #handler_wrap_func_body {
Ok(resp) => resp,
Err(err) => {
let handler = &__potato_error_handler;
match handler {
Some(potato::ErrorHandler::Async(h)) => h(req, err).await,
Some(potato::ErrorHandler::Sync(h)) => h(req, err),
None => potato::HttpResponse::error(format!("{err:?}")),
}
}
},
};
#(
if let Err(err) = #postprocess_adapters(
req,
&mut __potato_response,
__potato_once_cache.as_mut(),
__potato_session_cache.as_mut(),
).await {
drop(__potato_permit);
let handler = &__potato_error_handler;
return match handler {
Some(potato::ErrorHandler::Async(h)) => h(req, err).await,
Some(potato::ErrorHandler::Sync(h)) => h(req, err),
None => potato::HttpResponse::error(format!("{err:?}")),
};
}
)*
#add_headers_code
#cors_headers_code
// 自动应用SessionCache中的cookies到响应
if let Some(ref session_cache) = __potato_session_cache {
session_cache.apply_cookies(&mut __potato_response);
}
drop(__potato_permit);
__potato_response
}
} else {
quote! {
// 获取自定义错误处理器
let __potato_error_handler: Option<potato::ErrorHandler> = {
let mut handler = None;
for flag in potato::inventory::iter::<potato::ErrorHandlerFlag> {
handler = Some(flag.handler.clone());
break;
}
handler
};
// 按需创建缓存对象
let mut __potato_once_cache: Option<potato::OnceCache> = if #need_once_cache {
Some(potato::OnceCache::new())
} else {
None
};
let mut __potato_session_cache: Option<potato::SessionCache> = if #need_session_cache {
// 从 Authorization header 中提取 Bearer token 并加载 session
if let Some(h) = req.headers.get(&potato::utils::refstr::HeaderOrHipStr::from_str("Authorization")) {
let header_value = h.as_str();
if header_value.starts_with("Bearer ") {
potato::SessionCache::from_token(&header_value[7..]).await.ok()
} else {
None
}
} else {
None
}
} else {
None
};
// 如果 handler 需要 SessionCache 但没有提供 Authorization header,返回 401
if #need_session_cache && __potato_session_cache.is_none() {
let mut __potato_resp = potato::HttpResponse::text("Unauthorized: Missing or invalid Authorization header");
__potato_resp.http_code = 401;
return __potato_resp;
}
// 自动解析请求中的Cookie
if let Some(ref mut session_cache) = __potato_session_cache {
if let Some(cookie_header) = req.headers.get(&potato::utils::refstr::HeaderOrHipStr::from_str("Cookie")) {
session_cache.parse_request_cookies(cookie_header.as_str());
}
}
let mut __potato_pre_response: Option<potato::HttpResponse> = None;
#(
if __potato_pre_response.is_none() {
__potato_pre_response = match #preprocess_adapters(
req,
__potato_once_cache.as_mut(),
__potato_session_cache.as_mut(),
).await {
Ok(Some(ret)) => Some(ret),
Ok(None) => None,
Err(err) => {
let handler = &__potato_error_handler;
Some(match handler {
Some(potato::ErrorHandler::Async(h)) => h(req, err).await,
Some(potato::ErrorHandler::Sync(h)) => h(req, err),
None => potato::HttpResponse::error(format!("{err:?}")),
})
}
};
}
)*
let mut __potato_response = match __potato_pre_response {
Some(ret) => ret,
None => match #handler_wrap_func_body {
Ok(resp) => resp,
Err(err) => {
let handler = &__potato_error_handler;
match handler {
Some(potato::ErrorHandler::Async(h)) => h(req, err).await,
Some(potato::ErrorHandler::Sync(h)) => h(req, err),
None => potato::HttpResponse::error(format!("{err:?}")),
}
}
},
};
#(
if let Err(err) = #postprocess_adapters(
req,
&mut __potato_response,
__potato_once_cache.as_mut(),
__potato_session_cache.as_mut(),
).await {
let handler = &__potato_error_handler;
return match handler {
Some(potato::ErrorHandler::Async(h)) => h(req, err).await,
Some(potato::ErrorHandler::Sync(h)) => h(req, err),
None => potato::HttpResponse::error(format!("{err:?}")),
};
}
)*
#add_headers_code
#cors_headers_code
__potato_response
}
}
} else {
if max_concurrency.is_some() {
let semaphore_name =
format_ident!("__POTATO_SEMAPHORE_{}", fn_name.to_string().to_uppercase());
quote! {
let __potato_permit = #semaphore_name.acquire().await;
// 获取自定义错误处理器
let __potato_error_handler: Option<potato::ErrorHandler> = {
let mut handler = None;
for flag in potato::inventory::iter::<potato::ErrorHandlerFlag> {
handler = Some(flag.handler.clone());
break;
}
handler
};
// 按需创建缓存对象
let mut __potato_once_cache: Option<potato::OnceCache> = if #need_once_cache {
Some(potato::OnceCache::new())
} else {
None
};
let mut __potato_session_cache: Option<potato::SessionCache> = if #need_session_cache {
// 从 Authorization header 中提取 Bearer token 并加载 session
if let Some(h) = req.headers.get(&potato::utils::refstr::HeaderOrHipStr::from_str("Authorization")) {
let header_value = h.as_str();
if header_value.starts_with("Bearer ") {
potato::SessionCache::from_token(&header_value[7..]).await.ok()
} else {
None
}
} else {
None
}
} else {
None
};
// 如果 handler 需要 SessionCache 但没有提供 Authorization header,返回 401
if #need_session_cache && __potato_session_cache.is_none() {
let mut __potato_resp = potato::HttpResponse::text("Unauthorized: Missing or invalid Authorization header");
__potato_resp.http_code = 401;
return __potato_resp;
}
// 自动解析请求中的Cookie
if let Some(ref mut session_cache) = __potato_session_cache {
if let Some(cookie_header) = req.headers.get(&potato::utils::refstr::HeaderOrHipStr::from_str("Cookie")) {
session_cache.parse_request_cookies(cookie_header.as_str());
}
}
let mut __potato_pre_response: Option<potato::HttpResponse> = None;
#(
if __potato_pre_response.is_none() {
__potato_pre_response = match #preprocess_adapters(
req,
__potato_once_cache.as_mut(),
__potato_session_cache.as_mut(),
).await {
Ok(Some(ret)) => Some(ret),
Ok(None) => None,
Err(err) => {
let handler = &__potato_error_handler;
Some(match handler {
Some(potato::ErrorHandler::Async(h)) => h(req, err).await,
Some(potato::ErrorHandler::Sync(h)) => h(req, err),
None => potato::HttpResponse::error(format!("{err:?}")),
})
}
};
}
)*
let mut __potato_response = match __potato_pre_response {
Some(ret) => ret,
None => match #handler_wrap_func_body {
Ok(resp) => resp,
Err(err) => {
let handler = &__potato_error_handler;
match handler {
Some(potato::ErrorHandler::Async(h)) => h(req, err).await,
Some(potato::ErrorHandler::Sync(h)) => h(req, err),
None => potato::HttpResponse::error(format!("{err:?}")),
}
}
},
};
#(
if let Err(err) = #postprocess_adapters(
req,
&mut __potato_response,
__potato_once_cache.as_mut(),
__potato_session_cache.as_mut(),
).await {
drop(__potato_permit);
let handler = &__potato_error_handler;
return match handler {
Some(potato::ErrorHandler::Async(h)) => h(req, err).await,
Some(potato::ErrorHandler::Sync(h)) => h(req, err),
None => potato::HttpResponse::error(format!("{err:?}")),
};
}
)*
#add_headers_code
#cors_headers_code
// 自动应用SessionCache中的cookies到响应
if let Some(ref session_cache) = __potato_session_cache {
session_cache.apply_cookies(&mut __potato_response);
}
drop(__potato_permit);
__potato_response
}
} else {
quote! {
// 获取自定义错误处理器
let __potato_error_handler: Option<potato::ErrorHandler> = {
let mut handler = None;
for flag in potato::inventory::iter::<potato::ErrorHandlerFlag> {
handler = Some(flag.handler.clone());
break;
}
handler
};
// 按需创建缓存对象
let mut __potato_once_cache: Option<potato::OnceCache> = if #need_once_cache {
Some(potato::OnceCache::new())
} else {
None
};
let mut __potato_session_cache: Option<potato::SessionCache> = if #need_session_cache {
// 从 Authorization header 中提取 Bearer token 并加载 session
if let Some(h) = req.headers.get(&potato::utils::refstr::HeaderOrHipStr::from_str("Authorization")) {
let header_value = h.as_str();
if header_value.starts_with("Bearer ") {
potato::SessionCache::from_token(&header_value[7..]).await.ok()
} else {
None
}
} else {
None
}
} else {
None
};
// 如果 handler 需要 SessionCache 但没有提供 Authorization header,返回 401
if #need_session_cache && __potato_session_cache.is_none() {
let mut __potato_resp = potato::HttpResponse::text("Unauthorized: Missing or invalid Authorization header");
__potato_resp.http_code = 401;
return __potato_resp;
}
// 自动解析请求中的Cookie
if let Some(ref mut session_cache) = __potato_session_cache {
if let Some(cookie_header) = req.headers.get(&potato::utils::refstr::HeaderOrHipStr::from_str("Cookie")) {
session_cache.parse_request_cookies(cookie_header.as_str());
}
}
let mut __potato_pre_response: Option<potato::HttpResponse> = None;
#(
if __potato_pre_response.is_none() {
__potato_pre_response = match #preprocess_adapters(
req,
__potato_once_cache.as_mut(),
__potato_session_cache.as_mut(),
).await {
Ok(Some(ret)) => Some(ret),
Ok(None) => None,
Err(err) => {
let handler = &__potato_error_handler;
Some(match handler {
Some(potato::ErrorHandler::Async(h)) => h(req, err).await,
Some(potato::ErrorHandler::Sync(h)) => h(req, err),
None => potato::HttpResponse::error(format!("{err:?}")),
})
}
};
}
)*
let mut __potato_response = match __potato_pre_response {
Some(ret) => ret,
None => match #handler_wrap_func_body {
Ok(resp) => resp,
Err(err) => {
let handler = &__potato_error_handler;
match handler {
Some(potato::ErrorHandler::Async(h)) => h(req, err).await,
Some(potato::ErrorHandler::Sync(h)) => h(req, err),
None => potato::HttpResponse::error(format!("{err:?}")),
}
}
},
};
#(
if let Err(err) = #postprocess_adapters(
req,
&mut __potato_response,
__potato_once_cache.as_mut(),
__potato_session_cache.as_mut(),
).await {
let handler = &__potato_error_handler;
return match handler {
Some(potato::ErrorHandler::Async(h)) => h(req, err).await,
Some(potato::ErrorHandler::Sync(h)) => h(req, err),
None => potato::HttpResponse::error(format!("{err:?}")),
};
}
)*
#add_headers_code
#cors_headers_code
// 自动应用SessionCache中的cookies到响应
if let Some(ref session_cache) = __potato_session_cache {
session_cache.apply_cookies(&mut __potato_response);
}
__potato_response
}
}
};
if is_async {
quote! {
#root_fn
#auto_head_handler
#semaphore_static
#[doc(hidden)]
async fn #wrap_func_name2(req: &mut potato::HttpRequest) -> potato::HttpResponse {
#wrap_func_body
}
#[doc(hidden)]
fn #wrap_func_name(req: &mut potato::HttpRequest) -> std::pin::Pin<Box<dyn std::future::Future<Output = potato::HttpResponse> + Send + '_>> {
Box::pin(#wrap_func_name2(req))
}
potato::inventory::submit!{potato::RequestHandlerFlag::new(
potato::HttpMethod::#req_name,
#final_path_expr,
potato::HttpHandler::Async(#wrap_func_name),
potato::RequestHandlerFlagDoc::new(#doc_show, #doc_auth, #doc_summary, #doc_desp, #doc_args, #tag_expr)
)}
}
.into()
} else {
quote! {
#root_fn
#auto_head_handler
#semaphore_static
#[doc(hidden)]
async fn #wrap_func_name2(req: &mut potato::HttpRequest) -> potato::HttpResponse {
#wrap_func_body
}
#[doc(hidden)]
fn #wrap_func_name(req: &mut potato::HttpRequest) -> std::pin::Pin<Box<dyn std::future::Future<Output = potato::HttpResponse> + Send + '_>> {
Box::pin(#wrap_func_name2(req))
}
potato::inventory::submit!{potato::RequestHandlerFlag::new(
potato::HttpMethod::#req_name,
#final_path_expr,
potato::HttpHandler::Async(#wrap_func_name),
potato::RequestHandlerFlagDoc::new(#doc_show, #doc_auth, #doc_summary, #doc_desp, #doc_args, #tag_expr)
)}
}
.into()
}
//}.to_string();
//panic!("{content}");
//todo!()
}
#[proc_macro_attribute]
pub fn http_get(attr: TokenStream, input: TokenStream) -> TokenStream {
http_handler_macro(attr, input, "GET")
}
#[proc_macro_attribute]
pub fn http_post(attr: TokenStream, input: TokenStream) -> TokenStream {
http_handler_macro(attr, input, "POST")
}
#[proc_macro_attribute]
pub fn http_put(attr: TokenStream, input: TokenStream) -> TokenStream {
http_handler_macro(attr, input, "PUT")
}
#[proc_macro_attribute]
pub fn http_delete(attr: TokenStream, input: TokenStream) -> TokenStream {
http_handler_macro(attr, input, "DELETE")
}
#[proc_macro_attribute]
pub fn http_options(attr: TokenStream, input: TokenStream) -> TokenStream {
http_handler_macro(attr, input, "OPTIONS")
}
#[proc_macro_attribute]
pub fn http_head(attr: TokenStream, input: TokenStream) -> TokenStream {
http_handler_macro(attr, input, "HEAD")
}
/// Controller 属性宏 - 定义控制器结构体
///
/// # 功能
/// - 为结构体的 impl 块中的所有方法提供统一的路由前缀
/// - 支持 preprocess/postprocess 中间件继承
/// - 自动为 Swagger 文档分组(tag 为结构体名称)
///
/// # 结构体字段限制
/// 只能包含以下类型的字段(0个或多个):
/// - `&'a potato::OnceCache`
/// - `&'a potato::SessionCache`
///
/// # 示例
/// ```rust,ignore
/// #[potato::controller("/api/users")]
/// pub struct UsersController<'a> {
/// pub once_cache: &'a potato::OnceCache,
/// pub sess_cache: &'a potato::SessionCache,
/// }
///
/// #[potato::preprocess(my_preprocess)]
/// impl<'a> UsersController<'a> {
/// #[potato::http_get] // 地址为 "/api/users"
/// pub async fn get(&self) -> anyhow::Result<&'static str> {
/// Ok("get users data")
/// }
///
/// #[potato::http_get("/any")] // 地址为 "/api/users/any"
/// pub async fn get_any(&self) -> anyhow::Result<&'static str> {
/// Ok("get any data")
/// }
/// }
/// ```
#[proc_macro_attribute]
pub fn controller(attr: TokenStream, input: TokenStream) -> TokenStream {
controller_macro(attr, input)
}
fn controller_macro(attr: TokenStream, input: TokenStream) -> TokenStream {
// 尝试解析为 impl 块
let input_clone = input.clone();
if let Ok(item_impl) = syn::parse::<syn::ItemImpl>(input_clone) {
// 这是 impl 块,需要提取方法并生成路由注册
return controller_impl_macro(attr, item_impl);
}
// 否则解析为结构体
let item_struct = syn::parse_macro_input!(input as syn::ItemStruct);
// 解析 base path(结构体上的 controller 可以没有 path,由 impl 块指定)
let base_path = if attr.is_empty() {
// 结构体上没有 path,不生成常量,由 impl 块上的 controller 指定
quote! {}
} else {
let attr_str = attr.to_string();
let base_path = attr_str.trim_matches('"').to_string();
quote! {
#[doc(hidden)]
const __POTATO_CONTROLLER_BASE_PATH: &str = #base_path;
}
};
// 验证结构体字段并获取字段信息
let (has_once_cache, has_session_cache) = validate_controller_struct(&item_struct);
let struct_name = &item_struct.ident;
let struct_name_str = struct_name.to_string();
// 生成结构体定义、常量和 inventory 提交
// 同时生成隐藏的 controller 创建辅助函数
let controller_creation_fn = if has_session_cache {
// 结构体有 SessionCache 字段,生成包含鉴权的创建函数
// 直接创建并返回 Box<Self>
quote! {
#[doc(hidden)]
#[allow(dead_code)]
async fn __potato_create_controller(req: &potato::HttpRequest) -> Result<Box<Self>, potato::HttpResponse> {
// 在堆上分配缓存
let once_cache = Box::leak(Box::new(potato::OnceCache::new()));
// 从 Authorization header 中提取 Bearer token 并加载 session
let session_cache = {
if let Some(h) = req.headers.get(&potato::utils::refstr::HeaderOrHipStr::from_str("Authorization")) {
let header_value = h.as_str();
if header_value.starts_with("Bearer ") {
potato::SessionCache::from_token(&header_value[7..]).await.ok()
} else {
None
}
} else {
None
}
};
let session_cache = match session_cache {
Some(cache) => cache,
None => {
let mut resp = potato::HttpResponse::text("Unauthorized: Missing or invalid Authorization header");
resp.http_code = 401;
return Err(resp);
}
};
let session_cache = Box::leak(Box::new(session_cache));
// 创建 controller 实例
let controller = Self {
once_cache,
sess_cache: session_cache,
};
Ok(Box::new(controller))
}
}
} else {
// 结构体没有 SessionCache 字段,生成不包含鉴权的创建函数
// 创建临时的 SessionCache(但不使用),返回 Box<Self>
quote! {
#[doc(hidden)]
#[allow(dead_code)]
async fn __potato_create_controller(_req: &potato::HttpRequest) -> Result<Box<Self>, potato::HttpResponse> {
// 在堆上分配缓存
let once_cache = Box::leak(Box::new(potato::OnceCache::new()));
// 创建临时的 SessionCache(不需要鉴权,也不使用)
let _temp_session_cache = Box::leak(Box::new(potato::SessionCache::new()));
// 创建 controller 实例(不包含 sess_cache 字段)
let controller = Self {
once_cache,
};
Ok(Box::new(controller))
}
}
};
// 提取结构体的泛型参数(包括生命周期)
let struct_generics = &item_struct.generics;
let (impl_generics, type_generics, where_clause) = struct_generics.split_for_impl();
let output = quote! {
#item_struct
#base_path
#[doc(hidden)]
const __POTATO_CONTROLLER_NAME: &str = #struct_name_str;
// 提交 Controller 结构体字段信息到 inventory
potato::inventory::submit! {
potato::ControllerStructFlag::new(
#struct_name_str,
potato::ControllerStructFieldInfo {
has_once_cache: #has_once_cache,
has_session_cache: #has_session_cache,
}
)
}
// 生成隐藏的 controller 创建辅助函数
impl #impl_generics #struct_name #type_generics #where_clause {
#controller_creation_fn
}
};
output.into()
}
/// 处理 impl 块的 controller 宏
fn controller_impl_macro(attr: TokenStream, item_impl: syn::ItemImpl) -> TokenStream {
// 解析 base path(如果 attr 为空,则从常量读取)
let base_path_str = if attr.is_empty() {
// 从结构体上的 controller 宏生成的常量读取
// 这种情况暂不支持,因为宏展开时无法读取常量值
None
} else {
let attr_str = attr.to_string();
Some(attr_str.trim_matches('"').to_string())
};
// 从 impl 块中提取类型名称
let self_type = &item_impl.self_ty;
// 提取不带生命周期参数的类型名称(用于实例化)
let self_type_name = match &*item_impl.self_ty {
syn::Type::Path(type_path) => {
// 获取路径的最后一段(类型名称),不包含泛型参数
if let Some(segment) = type_path.path.segments.last() {
let ident = &segment.ident;
quote! { #ident }
} else {
quote! { #self_type }
}
}
_ => quote! { #self_type },
};
// 提取不带生命周期参数的类型名称字符串(用于 Swagger tag)
let self_type_tag = match &*item_impl.self_ty {
syn::Type::Path(type_path) => {
// 获取路径的最后一段(类型名称),不包含泛型参数
if let Some(segment) = type_path.path.segments.last() {
segment.ident.to_string()
} else {
self_type.to_token_stream().to_string()
}
}
_ => self_type.to_token_stream().to_string(),
};
// 创建清理后的 impl 块(移除方法上的 http_* 标注)
let mut cleaned_items = Vec::new();
let mut generated_code = Vec::new();
for item in &item_impl.items {
if let syn::ImplItem::Fn(method) = item {
// 检查是否有 http_* 标注
let has_http_attr = method.attrs.iter().any(|attr| {
let attr_name = attr.path().to_token_stream().to_string();
attr_name.contains("http_get")
|| attr_name.contains("http_post")
|| attr_name.contains("http_put")
|| attr_name.contains("http_delete")
|| attr_name.contains("http_head")
|| attr_name.contains("http_patch")
|| attr_name.contains("http_options")
});
if has_http_attr {
// 有 http_* 标注,创建清理后的方法(移除 http_* 标注)
let mut cleaned_method = method.clone();
cleaned_method.attrs = method
.attrs
.iter()
.filter(|attr| {
let attr_name = attr.path().to_token_stream().to_string();
!attr_name.contains("http_get")
&& !attr_name.contains("http_post")
&& !attr_name.contains("http_put")
&& !attr_name.contains("http_delete")
&& !attr_name.contains("http_head")
&& !attr_name.contains("http_patch")
&& !attr_name.contains("http_options")
})
.cloned()
.collect();
cleaned_items.push(syn::ImplItem::Fn(cleaned_method));
// 为每个 http_* 标注生成包装函数和路由注册
for attr in &method.attrs {
let attr_name = attr.path().to_token_stream().to_string();
if attr_name.contains("http_get")
|| attr_name.contains("http_post")
|| attr_name.contains("http_put")
|| attr_name.contains("http_delete")
|| attr_name.contains("http_head")
|| attr_name.contains("http_patch")
|| attr_name.contains("http_options")
{
// 提取 HTTP 方法名
let http_method = if attr_name.contains("http_get") {
"GET"
} else if attr_name.contains("http_post") {
"POST"
} else if attr_name.contains("http_put") {
"PUT"
} else if attr_name.contains("http_delete") {
"DELETE"
} else if attr_name.contains("http_head") {
"HEAD"
} else if attr_name.contains("http_patch") {
"PATCH"
} else {
"OPTIONS"
};
// 提取 path 参数
let method_path = match &attr.meta {
syn::Meta::List(list) => {
if let Ok(lit_str) =
syn::parse::<syn::LitStr>(list.tokens.clone().into())
{
lit_str.value()
} else {
String::new()
}
}
_ => String::new(),
};
// 拼接路径(在宏展开时完成)
let final_path = if let Some(ref base_path) = base_path_str {
// base path 已知,直接在宏展开时拼接
if method_path.is_empty() {
base_path.clone()
} else {
format!("{}{}", base_path, method_path)
}
} else {
// base path 未知(从常量读取),这种情况暂不支持
panic!("impl block controller must specify a base path, e.g., #[potato::controller(\"/api/users\")]");
};
// 将 final_path 转换为 LitStr
let final_path_lit =
syn::LitStr::new(&final_path, proc_macro2::Span::call_site());
// 生成包装函数名
let fn_name = &method.sig.ident;
let wrapper_fn_name = quote::format_ident!("__potato_ctrl_{}", fn_name);
let is_async = method.sig.asyncness.is_some();
// 检测方法是否有 receiver,以及是否是 mutable
let (has_receiver, _is_mut_receiver) = method
.sig
.inputs
.iter()
.filter_map(|arg| {
if let syn::FnArg::Receiver(recv) = arg {
Some((true, recv.mutability.is_some()))
} else {
None
}
})
.next()
.unwrap_or((false, false));
// 提取非 receiver 参数
let other_params: Vec<_> = method
.sig
.inputs
.iter()
.filter_map(|arg| {
if let syn::FnArg::Typed(pat_type) = arg {
Some(pat_type.clone())
} else {
None
}
})
.collect();
// 检测非 receiver 参数中是否包含 SessionCache
let method_has_session_cache = other_params.iter().any(|pat_type| {
pat_type.ty.to_token_stream().to_string().type_simplify()
== "& mut SessionCache"
});
// 如果方法有 receiver(&self 或 &mut self),或者参数包含 SessionCache,则需要鉴权
let doc_auth = has_receiver || method_has_session_cache;
// 提取参数名
let param_names: Vec<_> = other_params
.iter()
.filter_map(|pat_type| {
if let syn::Pat::Ident(pat_ident) = &*pat_type.pat {
Some(pat_ident.ident.clone())
} else {
None
}
})
.collect();
// 生成方法调用
let method_call = if has_receiver {
// 有 receiver,需要实例化 controller
// 使用结构体生成的 __potato_create_controller 函数
// 返回 Box<Self>
if param_names.is_empty() {
if is_async {
quote! {
{
let mut controller = match #self_type_name::__potato_create_controller(req).await {
Ok(boxed) => boxed,
Err(resp) => return resp,
};
controller.#fn_name().await
}
}
} else {
quote! {
{
let mut controller = match #self_type_name::__potato_create_controller(req).await {
Ok(boxed) => boxed,
Err(resp) => return resp,
};
controller.#fn_name()
}
}
}
} else {
if is_async {
quote! {
{
let mut controller = match #self_type_name::__potato_create_controller(req).await {
Ok(boxed) => boxed,
Err(resp) => return resp,
};
controller.#fn_name(#(#param_names),*).await
}
}
} else {
quote! {
{
let mut controller = match #self_type_name::__potato_create_controller(req).await {
Ok(boxed) => boxed,
Err(resp) => return resp,
};
controller.#fn_name(#(#param_names),*)
}
}
}
}
} else {
// 没有 receiver,直接调用关联函数
// 但仍需要处理参数(如 SessionCache)
if param_names.is_empty() {
if is_async {
quote! { #self_type_name::#fn_name().await }
} else {
quote! { #self_type_name::#fn_name() }
}
} else {
// 有参数,需要根据参数类型生成绑定代码
// 生成参数绑定
let mut param_bindings = Vec::new();
for (i, param) in other_params.iter().enumerate() {
let param_type_str =
param.ty.to_token_stream().to_string().type_simplify();
let param_name = ¶m_names[i];
match ¶m_type_str[..] {
"& mut OnceCache" => {
param_bindings.push(quote! {
let #param_name = &mut __potato_once_cache;
});
}
"& mut SessionCache" => {
param_bindings.push(quote! {
let #param_name = &mut __potato_session_cache;
});
}
_ => {
// 其他参数类型暂不支持
}
}
}
// 生成 SessionCache 加载逻辑(从 Authorization header)
let needs_session_cache = other_params.iter().any(|p| {
p.ty.to_token_stream().to_string().type_simplify()
== "& mut SessionCache"
});
let session_cache_init = if needs_session_cache {
quote! {
{
// 从 Authorization header 中提取 Bearer token 并加载 session
if let Some(h) = req.headers.get(&potato::utils::refstr::HeaderOrHipStr::from_str("Authorization")) {
let header_value = h.as_str();
if header_value.starts_with("Bearer ") {
potato::SessionCache::from_token(&header_value[7..]).await.ok()
} else {
None
}
} else {
None
}
}
}
} else {
quote! { None }
};
if is_async {
quote! {
{
let mut __potato_once_cache = potato::OnceCache::new();
let mut __potato_session_cache = #session_cache_init.unwrap_or_else(|| potato::SessionCache::new());
#(#param_bindings)*
#self_type_name::#fn_name(#(#param_names),*).await
}
}
} else {
quote! {
{
let mut __potato_once_cache = potato::OnceCache::new();
let mut __potato_session_cache = #session_cache_init.unwrap_or_else(|| potato::SessionCache::new());
#(#param_bindings)*
#self_type_name::#fn_name(#(#param_names),*)
}
}
}
}
};
// 生成包装函数 - 简化版,直接返回文本
let wrapper_fn = if is_async {
quote! {
#[doc(hidden)]
fn #wrapper_fn_name(req: &mut potato::HttpRequest) -> std::pin::Pin<Box<dyn std::future::Future<Output = potato::HttpResponse> + Send + '_>> {
Box::pin(async move {
match #method_call {
Ok(resp) => potato::HttpResponse::text(resp.to_string()),
Err(err) => potato::HttpResponse::error(err.to_string()),
}
})
}
}
} else {
quote! {
#[doc(hidden)]
fn #wrapper_fn_name(req: &mut potato::HttpRequest) -> std::pin::Pin<Box<dyn std::future::Future<Output = potato::HttpResponse> + Send + '_>> {
Box::pin(async move {
match #method_call {
Ok(resp) => potato::HttpResponse::text(resp.to_string()),
Err(err) => potato::HttpResponse::error(err.to_string()),
}
})
}
}
};
generated_code.push(wrapper_fn);
// 生成路由注册
let http_method_ident = quote::format_ident!("{}", http_method);
let route_register = quote! {
potato::inventory::submit! {
potato::RequestHandlerFlag::new(
potato::HttpMethod::#http_method_ident,
#final_path_lit,
potato::HttpHandler::Async(#wrapper_fn_name),
potato::RequestHandlerFlagDoc::new(true, #doc_auth, "", "", "", #self_type_tag)
)
}
};
generated_code.push(route_register);
}
}
} else {
// 没有 http_* 标注,保留原方法
cleaned_items.push(item.clone());
}
} else {
// 非方法项,直接保留
cleaned_items.push(item.clone());
}
}
// 生成清理后的 impl 块
let mut cleaned_impl = item_impl.clone();
cleaned_impl.items = cleaned_items;
// 生成最终代码:清理后的 impl 块 + 生成的独立函数和路由注册
let output = quote! {
#cleaned_impl
#(#generated_code)*
};
output.into()
}
#[proc_macro_attribute]
pub fn preprocess(attr: TokenStream, input: TokenStream) -> TokenStream {
preprocess_macro(attr, input)
}
#[proc_macro_attribute]
pub fn postprocess(attr: TokenStream, input: TokenStream) -> TokenStream {
postprocess_macro(attr, input)
}
/// handle_error 属性宏 - 定义全局错误处理函数
///
/// # 签名要求
/// - 参数1: `req: &mut HttpRequest`
/// - 参数2: `err: anyhow::Error`
/// - 返回: `HttpResponse`
/// - 支持 async fn 和普通 fn
///
/// # 示例
/// ```rust,ignore
/// #[potato::handle_error]
/// async fn handle_error(req: &mut HttpRequest, err: anyhow::Error) -> HttpResponse {
/// HttpResponse::json(serde_json::json!({
/// "error": format!("{}", err)
/// }))
/// }
/// ```
fn handle_error_macro(attr: TokenStream, input: TokenStream) -> TokenStream {
if !attr.is_empty() {
return input;
}
let root_fn = syn::parse_macro_input!(input as syn::ItemFn);
let fn_name = root_fn.sig.ident.clone();
let is_async = root_fn.sig.asyncness.is_some();
// 验证函数签名
if root_fn.sig.inputs.len() != 2 {
panic!("`handle_error` function must accept exactly two arguments");
}
let mut arg_types = vec![];
for arg in root_fn.sig.inputs.iter() {
match arg {
syn::FnArg::Typed(arg) => {
arg_types.push(arg.ty.to_token_stream().to_string().type_simplify())
}
_ => panic!("`handle_error` function does not support receiver argument"),
}
}
if arg_types[0] != "& mut HttpRequest" {
panic!(
"`handle_error` first argument must be `&mut potato::HttpRequest`, got `{}`",
arg_types[0]
);
}
if arg_types[1] != "anyhow::Error" {
panic!(
"`handle_error` second argument must be `anyhow::Error`, got `{}`",
arg_types[1]
);
}
let ret_type = root_fn
.sig
.output
.to_token_stream()
.to_string()
.type_simplify();
if ret_type != "HttpResponse" {
panic!(
"`handle_error` return type must be `potato::HttpResponse`, got `{}`",
ret_type
);
}
// 生成适配器函数
let wrap_name = format_ident!("__potato_error_handler_adapter_{}", fn_name);
let wrap_name_inner = format_ident!("__potato_error_handler_adapter_inner_{}", fn_name);
// 生成内部函数
let call_body = if is_async {
quote! { #fn_name(req, err).await }
} else {
quote! { #fn_name(req, err) }
};
quote! {
#root_fn
#[doc(hidden)]
async fn #wrap_name_inner(
req: &mut potato::HttpRequest,
err: anyhow::Error,
) -> potato::HttpResponse {
#call_body
}
#[doc(hidden)]
pub fn #wrap_name(
req: &mut potato::HttpRequest,
err: anyhow::Error,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = potato::HttpResponse> + Send + '_>> {
Box::pin(#wrap_name_inner(req, err))
}
potato::inventory::submit! {
potato::ErrorHandlerFlag::new(
potato::ErrorHandler::Async(#wrap_name)
)
}
}
.into()
}
#[proc_macro_attribute]
pub fn handle_error(attr: TokenStream, input: TokenStream) -> TokenStream {
handle_error_macro(attr, input)
}
/// limit_size 属性宏 - 为 handler 设置独立的请求体大小限制
///
/// # 参数
/// * 单个值: `#[potato::limit_size(1024 * 1024 * 1024)]` - 仅限制 body 为 1GB
/// * 命名参数: `#[potato::limit_size(header = 2 * 1024 * 1024, body = 500 * 1024 * 1024)]`
///
/// # 示例
/// ```rust,ignore
/// // 限制 body 为 1GB
/// #[potato::http_post("/upload")]
/// #[potato::limit_size(1024 * 1024 * 1024)]
/// async fn large_upload(req: &mut potato::HttpRequest) -> potato::HttpResponse {
/// todo!()
/// }
///
/// // 分别限制 header 和 body
/// #[potato::http_post("/upload")]
/// #[potato::limit_size(header = 2 * 1024 * 1024, body = 500 * 1024 * 1024)]
/// async fn medium_upload(req: &mut potato::HttpRequest) -> potato::HttpResponse {
/// todo!()
/// }
/// ```
#[proc_macro_attribute]
pub fn limit_size(attr: TokenStream, input: TokenStream) -> TokenStream {
limit_size_macro(attr, input)
}
fn limit_size_macro(attr: TokenStream, input: TokenStream) -> TokenStream {
// 解析参数
let (_max_header, max_body) = {
let attr_tokens: proc_macro2::TokenStream = attr.clone().into();
if attr_tokens.is_empty() {
// 默认值: 不限制 header,使用全局 body 限制
(None, None)
} else {
// 尝试解析为命名参数或单值
let result = syn::parse::Parser::parse2(
|input: syn::parse::ParseStream| -> syn::Result<(Option<syn::Expr>, Option<syn::Expr>)> {
let mut header_expr = None;
let mut body_expr = None;
// 尝试解析命名参数
while !input.is_empty() {
let ident: Ident = input.parse()?;
input.parse::<Token![=]>()?;
let value: syn::Expr = input.parse()?;
match ident.to_string().as_str() {
"header" => header_expr = Some(value),
"body" => body_expr = Some(value),
_ => return Err(syn::Error::new(ident.span(), "expected 'header' or 'body'")),
}
// 可选的逗号
if input.peek(Token![,]) {
input.parse::<Token![,]>()?;
}
}
Ok((header_expr, body_expr))
},
attr_tokens.clone(),
);
match result {
Ok((h, b)) => (h, b),
Err(_) => {
// 解析失败,尝试作为单值(body 限制)
if let Ok(expr) = syn::parse2::<syn::Expr>(attr_tokens) {
(None, Some(expr))
} else {
(None, None)
}
}
}
}
};
let root_fn = syn::parse_macro_input!(input as syn::ItemFn);
// 生成检查代码
let body_check = if let Some(body_expr) = max_body {
quote! {
// 检查 body 大小
let body_len = req.body.len();
if body_len > #body_expr {
let mut res = potato::HttpResponse::text(format!(
"Payload Too Large: body size {} bytes exceeds limit {} bytes",
body_len, #body_expr
));
res.http_code = 413;
return res;
}
}
} else {
quote! {}
};
// 克隆整个函数,然后修改 block
let mut wrapped_fn = root_fn.clone();
let original_block = root_fn.block.as_ref();
let new_block: syn::Block = syn::parse_quote!({
#body_check
#original_block
});
wrapped_fn.block = Box::new(new_block);
quote! {
#wrapped_fn
}
.into()
}
/// header 属性宏 - 这是一个占位宏,实际解析在 http_handler_macro 中完成
/// 这个宏的存在使得 #[potato::header(...)] 语法能够被编译器识别
#[proc_macro_attribute]
pub fn header(_attr: TokenStream, input: TokenStream) -> TokenStream {
// 直接返回原始函数,不做任何修改
// 实际的 header 解析和处理在 http_get/http_post 等宏中完成
input
}
/// cors 属性宏 - 这是一个占位宏,实际解析在 http_handler_macro 中完成
/// 这个宏的存在使得 #[potato::cors(...)] 语法能够被编译器识别
#[proc_macro_attribute]
pub fn cors(_attr: TokenStream, input: TokenStream) -> TokenStream {
// 直接返回原始函数,不做任何修改
// 实际的 cors 解析和处理在 http_handler_macro 中完成
input
}
#[proc_macro]
pub fn embed_dir(input: TokenStream) -> TokenStream {
let path = syn::parse_macro_input!(input as syn::LitStr).value();
quote! {{
#[derive(potato::rust_embed::Embed)]
#[folder = #path]
struct Asset;
potato::load_embed::<Asset>()
}}
.into()
}
#[proc_macro_derive(StandardHeader)]
pub fn standard_header_derive(input: TokenStream) -> TokenStream {
let root_enum = syn::parse_macro_input!(input as syn::ItemEnum);
let enum_name = root_enum.ident;
let mut try_from_str_items = vec![];
let mut to_str_items = vec![];
let mut headers_items = vec![];
let mut headers_apply_items = vec![];
for root_field in root_enum.variants.iter() {
let name = root_field.ident.clone();
if root_field.fields.iter().next().is_some() {
panic!("unsupported enum type");
}
let str_name = name.to_string().replace("_", "-");
let len = str_name.len();
try_from_str_items
.push(quote! { #len if value.eq_ignore_ascii_case(#str_name) => Some(Self::#name), });
to_str_items.push(quote! { Self::#name => #str_name, });
headers_items.push(quote! { #name(String), });
headers_apply_items
.push(quote! { Headers::#name(s) => self.set_header(HeaderItem::#name.to_str(), s), });
}
let r = quote! {
impl #enum_name {
pub fn try_from_str(value: &str) -> Option<Self> {
match value.len() {
#( #try_from_str_items )*
_ => None,
}
}
pub fn to_str(&self) -> &'static str {
match self {
#( #to_str_items )*
}
}
}
pub enum Headers {
#( #headers_items )*
Custom((String, String)),
}
impl HttpRequest {
pub fn apply_header(&mut self, header: Headers) {
match header {
#( #headers_apply_items )*
Headers::Custom((k, v)) => self.set_header(&k[..], v),
}
}
}
};
r.into()
}