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
use crate::error::{Error, Result};
use crate::http::request::short_type_name;
use crate::http::{Body, FileCollection, FormData, FormValue, Request, Response, UploadedFile};
use crate::session::Session;
use crate::views::ViewEngine;
use hyper::StatusCode;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::any::Any;
use std::collections::HashMap;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
/// HTTP request context focused on request/response operations
///
/// Context handles only HTTP-related concerns following clean architecture principles.
/// Models and modules are accessed directly via imports, not through service locators.
/// Configuration is accessed through the global CONF, not through Context.
///
/// ## Typed Parameter Access
///
/// For typed query/route/body parameter access, prefer **source-first** method names for better discoverability:
/// - Query parameters: [`query_str`](Self::query_str), [`query_int`](Self::query_int), [`query_bool`](Self::query_bool)
/// - Route parameters: [`param_str`](Self::param_str), [`param_int`](Self::param_int)
/// - Body fields: [`body_str`](Self::body_str), [`body_int`](Self::body_int), [`body_bool`](Self::body_bool)
///
/// These methods are easier to find when exploring the API (e.g., searching for "query" shows `query_int`).
/// Type-first names (`int_query`, `str_param`, `str_body`) are still available but delegate to the source-first methods.
pub struct Context {
pub req: Request,
pub res: Option<Response>,
session: Option<Arc<Session>>,
views: Arc<ViewEngine>,
layout_name: Option<String>,
/// Per-request repository for controller-specific data accessible in views.
///
/// Held as a `Value::Object` rather than a `HashMap` so `view` can hand the
/// engine `&self.repository` directly instead of rebuilding (and deep-cloning)
/// a `Value` on every render. Invariant: always `Value::Object`.
repository: Value,
/// Storage for middleware data (not accessible in views)
data: HashMap<String, Box<dyn Any + Send + Sync>>,
/// Signals that the session must be removed from storage and the cookie
/// cleared in the outbound middleware.
session_destroyed: AtomicBool,
/// Cached form data to avoid re-parsing
/// Cached form data with array support
cached_form_data_arrays: Option<Result<HashMap<String, FormValue>>>,
/// The matched route's `SOCKET` settings, copied in by the dispatcher.
///
/// `Some` only while a `SOCKET` route's handler is running; that is what
/// lets `ctx.websocket` / `ctx.socket` refuse to upgrade from an ordinary
/// `GET` route, which would otherwise silently skip the `426` guard.
pub(crate) socket_options: Option<crate::routing::SocketOptions>,
/// An upgrade the handler asked for, picked up by the dispatcher once the
/// handler returns. See `websocket::upgrade`.
#[cfg(feature = "websocket")]
pub(crate) pending_upgrade: Option<crate::websocket::upgrade::PendingUpgrade>,
}
// Context is automatically Send + Sync due to Arc<T> being Send + Sync
impl Context {
/// Create a new HTTP-focused context
///
/// Context handles only HTTP request/response concerns.
/// Configuration should be accessed through the global CONF.
pub fn new(request: Request, views: Arc<ViewEngine>) -> Self {
// Get default layout from global config, fallback to "layouts/default"
let default_layout = crate::configuration::CONF::get_string("views.default_layout")
.unwrap_or_else(|| "layouts/default".to_string());
Self {
req: request,
res: Some(Response::ok()), // Initialize with default 200 OK response
session: None,
views,
layout_name: Some(default_layout),
repository: Value::Object(serde_json::Map::new()),
data: HashMap::new(),
session_destroyed: AtomicBool::new(false),
cached_form_data_arrays: None,
socket_options: None,
#[cfg(feature = "websocket")]
pending_upgrade: None,
}
}
// Response management methods
/// Set the response for this context
pub fn set_response(&mut self, response: Response) {
self.res = Some(response);
}
/// Get the response if set
pub fn get_response(&self) -> Option<&Response> {
self.res.as_ref()
}
/// Take the response, leaving None in its place
pub fn take_response(&mut self) -> Option<Response> {
self.res.take()
}
/// Take the queued WebSocket upgrade, if the handler accepted one.
///
/// Called by the dispatcher after the handler returns; see
/// `websocket::upgrade` for why the upgrade cannot happen inline.
#[cfg(feature = "websocket")]
pub(crate) fn take_pending_upgrade(
&mut self,
) -> Option<crate::websocket::upgrade::PendingUpgrade> {
self.pending_upgrade.take()
}
/// Update response body and content-type while preserving other headers
/// This is used internally by response methods to avoid losing middleware-set headers
fn update_response_body(
&mut self,
body: Vec<u8>,
content_type: &str,
status: Option<StatusCode>,
) {
let response = self.res.as_mut().unwrap(); // Safe - always exists
// Update status if provided
if let Some(new_status) = status {
response.status = new_status;
}
// Update body
response.body = body.into();
// Update Content-Type (remove old, add new)
response
.headers
.retain(|(name, _)| name.to_lowercase() != "content-type");
response.add_header("Content-Type", content_type);
}
/// Update response preserving non-content headers
/// Used for complex responses that need multiple headers like file downloads
fn update_response(&mut self, mut new_response: Response) {
let response = self.res.as_mut().unwrap(); // Safe - always exists
// Collect non-content headers to preserve
let preserved: Vec<_> = response
.headers
.iter()
.filter(|(name, _)| !name.to_lowercase().starts_with("content-"))
.cloned()
.collect();
// Add preserved headers to new response if not already present
for (name, value) in preserved {
if !new_response.headers.iter().any(|(n, _)| n == &name) {
new_response.headers.push((name, value));
}
}
// Replace with updated response
*response = new_response;
}
// Middleware data storage methods
/// Store data for middleware communication
pub fn set<T: Any + Send + Sync + 'static>(&mut self, key: &str, value: T) -> Result<()> {
self.data.insert(key.to_string(), Box::new(value));
Ok(())
}
/// Retrieve data stored by middleware
pub fn get<T: Any + Send + Sync + 'static>(&self, key: &str) -> Option<&T> {
self.data
.get(key)
.and_then(|boxed| boxed.downcast_ref::<T>())
}
/// Check if data exists
pub fn has_data(&self, key: &str) -> bool {
self.data.contains_key(key)
}
// Session management methods
/// Set session (used by middleware)
pub fn set_session(&mut self, session: Option<Arc<Session>>) {
self.session = session;
if self.session.is_some() {
self.session_destroyed.store(false, Ordering::Relaxed);
}
}
/// Get session reference
pub fn session(&self) -> Option<&Session> {
self.session.as_deref()
}
/// Get session Arc (for middleware)
pub fn session_arc(&self) -> Option<&Arc<Session>> {
self.session.as_ref()
}
/// Check if session exists
pub fn has_session(&self) -> bool {
self.session.is_some()
}
/// Require session (returns error if missing)
pub fn require_session(&self) -> Result<&Session> {
self.session()
.ok_or_else(|| Error::authentication("Session required"))
}
/// Require authenticated session
pub fn require_auth(&self) -> Result<&Session> {
let session = self.require_session()?;
if !session.is_authenticated() {
return Err(Error::authentication("Authentication required"));
}
Ok(session)
}
/// Login user (marks session for rotation)
pub fn login(&self, user_id: i64) -> Result<()> {
let session = self.require_session()?;
session.set_user_id(user_id)?;
session.set_privilege_level(1);
session.mark_for_rotation();
Ok(())
}
/// Logout user (clears session)
pub fn logout(&self) -> Result<()> {
self.session_destroy();
Ok(())
}
// Flash message helpers (stored in session)
/// Set flash message
pub fn flash(&self, key: &str, value: impl serde::Serialize) -> Result<()> {
let session = self.require_session()?;
session.flash_set(key, value)?;
Ok(())
}
/// Get and consume flash message
pub fn get_flash(&self, key: &str) -> Option<Value> {
let session = self.session()?;
session.flash_get::<Value>(key)
}
/// Get all flash messages and clear them
pub fn get_all_flash(&self) -> HashMap<String, Value> {
let Some(session) = self.session() else {
return HashMap::new();
};
session.flash_get_all()
}
// Total.js style methods
/// Set the layout template (empty string for no layout)
pub fn layout(&mut self, name: &str) -> &mut Self {
self.layout_name = if name.is_empty() {
None
} else {
Some(name.to_string())
};
self
}
// Repository methods for per-request data
/// Set a value in the request-scoped repository, readable in views as
/// `@{R.key}` (or `@{repository.key}`).
///
/// This is the channel for **everything the page needs that is not its
/// single subject**: title, CSRF token, collections, navigation, counters,
/// permission flags. Call it once per key, as each piece of data becomes
/// available — including from middleware and modules, which hold
/// `&mut Context` and can contribute before the handler runs.
///
/// Do not assemble a large `json!({...})` and pass it to
/// [`view`](Self::view) instead. The model argument carries one simple
/// object — see [`view`](Self::view) for the split.
///
/// ```rust,ignore
/// ctx.repository_set("title", "Edit task");
/// ctx.repository_set("items", serde_json::to_value(&items)?);
/// ```
///
/// # Cost
///
/// `Context` hands the engine a borrow of this object, so no clone happens
/// here. The engine then deep-clones it once when it builds its render
/// context — the same cost the model passed to [`view`](Self::view) pays.
/// Both channels are therefore equal-cost; that remaining clone is an
/// implementation detail slated to be removed. Do not reshape a page around
/// it — put each piece of data in the channel it belongs to.
pub fn repository_set(&mut self, key: &str, value: impl Into<Value>) -> &mut Self {
// Invariant upheld by `new` and `repository_clear`.
if let Some(map) = self.repository.as_object_mut() {
map.insert(key.to_string(), value.into());
}
self
}
/// Get a value from the request-scoped repository
pub fn repository_get(&self, key: &str) -> Option<&Value> {
self.repository.as_object()?.get(key)
}
/// Clear the request-scoped repository
pub fn repository_clear(&mut self) -> &mut Self {
self.repository = Value::Object(serde_json::Map::new());
self
}
/// Render a view template with its model.
///
/// # What belongs in `data`
///
/// `data` becomes the view's model, read as `@{M.field}` (or
/// `@{model.field}`). It carries **one simple object**: the record or form
/// the page is about. Typically `serde_json::to_value(&record)?`.
///
/// Everything else — title, CSRF token, collections, navigation, counters —
/// goes through [`repository_set`](Self::repository_set) and is read as
/// `@{R.key}`. A page with no single subject (a list, a dashboard) passes
/// `json!({})` here and puts its data in the repository.
///
/// ```rust,ignore
/// // Detail page: the record is the model.
/// ctx.repository_set("title", "Task detail");
/// ctx.view("tasks/show", serde_json::to_value(&task)?)
///
/// // List page: no single subject.
/// ctx.repository_set("title", "Tasks");
/// ctx.repository_set("items", serde_json::to_value(&tasks)?);
/// ctx.view("tasks/index", json!({}))
/// ```
///
/// Do **not** collect unrelated page data into one large `json!({...})`
/// here. `data` has a single write point, so anything cross-cutting has to
/// be rebuilt by hand in every handler; the repository accumulates across
/// middleware, modules, and the handler.
///
/// # Concurrency
///
/// Rendering is CPU-bound and runs **synchronously on the current async
/// worker thread** — there is no `.await` inside the template engine, so the
/// worker is occupied for the full render duration. With the template cache
/// (very high hit rate) most renders are microsecond-scale and this is a
/// non-issue. But a pathologically large template or data payload can pin a
/// worker and raise tail latency for other requests sharing the runtime.
/// If you knowingly render heavy pages, offload with
/// [`tokio::task::spawn_blocking`] / [`tokio::task::block_in_place`].
/// A threshold-gated offload inside the framework is tracked as future work.
pub fn view(&mut self, template: &str, data: Value) -> Result<()> {
let views = Arc::clone(&self.views);
// Build per-request session Value if a session is active
let session_value = if let Some(session) = self.session() {
let flash = session.flash_peek_all();
let mut session_data = session.to_value();
if let Value::Object(ref mut map) = session_data {
map.insert("id".to_string(), Value::String(session.id().to_string()));
map.insert(
"authenticated".to_string(),
Value::Bool(session.is_authenticated()),
);
map.insert(
"user_id".to_string(),
session
.get_user_id()
.map(|id| Value::Number(id.into()))
.unwrap_or(Value::Null),
);
map.insert(
"flash".to_string(),
Value::Object(flash.into_iter().collect()),
);
}
Some(session_data)
} else {
None
};
// Per-request metadata for @{url} / @{hostname} / @{mobile}.
let request_meta = crate::views::RequestMeta {
url: self.req.path().to_string(),
hostname: self.req.hostname(None),
mobile: self
.req
.user_agent()
.map(crate::views::is_mobile)
.unwrap_or(false),
};
// Pass repository and session as separate arguments — avoids hidden-field
// packing and the data.clone() needed to strip those fields in the engine.
let rendered = views.render_rich(
template,
&data,
self.layout_name.as_deref(),
Some(&self.repository),
session_value.as_ref(),
Some(&request_meta),
)?;
if let Some(session) = self.session() {
if !session.flash_peek_all().is_empty() {
session.flash_clear();
}
}
self.update_response_body(rendered.into_bytes(), "text/html; charset=utf-8", None);
Ok(())
}
/// Redirect to another URL
pub fn redirect(&mut self, path: &str) -> Result<()> {
let redirect = Response::redirect(path)?;
self.update_response(redirect);
Ok(())
}
/// Redirect permanently to a local application path.
pub fn redirect_permanent(&mut self, path: &str) -> Result<()> {
let redirect = Response::redirect_permanent(path)?;
self.update_response(redirect);
Ok(())
}
/// Redirect to an external URL explicitly.
pub fn redirect_external(&mut self, url: &str) -> Result<()> {
let redirect = Response::redirect_external(url);
self.update_response(redirect);
Ok(())
}
/// Redirect permanently to an external URL explicitly.
pub fn redirect_external_permanent(&mut self, url: &str) -> Result<()> {
let redirect = Response::redirect_external_permanent(url);
self.update_response(redirect);
Ok(())
}
/// Return a 404 response
pub fn view404(&mut self) -> Result<()> {
self.update_response_body(
b"Not Found".to_vec(),
"text/plain; charset=utf-8",
Some(StatusCode::NOT_FOUND),
);
Ok(())
}
// Total.js-style HTTP error responses
/// Return 400 Bad Request response
pub fn throw400(&mut self, message: Option<&str>) -> Result<()> {
let body = message.unwrap_or("Bad Request");
self.update_response_body(
body.as_bytes().to_vec(),
"text/plain; charset=utf-8",
Some(StatusCode::BAD_REQUEST),
);
Ok(())
}
/// Return 401 Unauthorized response
pub fn throw401(&mut self, message: Option<&str>) -> Result<()> {
let body = message.unwrap_or("Unauthorized");
self.update_response_body(
body.as_bytes().to_vec(),
"text/plain; charset=utf-8",
Some(StatusCode::UNAUTHORIZED),
);
Ok(())
}
/// Return 403 Forbidden response
pub fn throw403(&mut self, message: Option<&str>) -> Result<()> {
let body = message.unwrap_or("Forbidden");
self.update_response_body(
body.as_bytes().to_vec(),
"text/plain; charset=utf-8",
Some(StatusCode::FORBIDDEN),
);
Ok(())
}
/// Return 404 Not Found response with optional custom message
pub fn throw404(&mut self, message: Option<&str>) -> Result<()> {
let body = message.unwrap_or("Not Found");
self.update_response_body(
body.as_bytes().to_vec(),
"text/plain; charset=utf-8",
Some(StatusCode::NOT_FOUND),
);
Ok(())
}
/// Return 409 Conflict response
pub fn throw409(&mut self, message: Option<&str>) -> Result<()> {
let body = message.unwrap_or("Conflict");
self.update_response_body(
body.as_bytes().to_vec(),
"text/plain; charset=utf-8",
Some(StatusCode::CONFLICT),
);
Ok(())
}
/// Return 500 Internal Server Error response
pub fn throw500(&mut self, message: Option<&str>) -> Result<()> {
let body = message.unwrap_or("Internal Server Error");
self.update_response_body(
body.as_bytes().to_vec(),
"text/plain; charset=utf-8",
Some(StatusCode::INTERNAL_SERVER_ERROR),
);
Ok(())
}
/// Return 501 Not Implemented response
pub fn throw501(&mut self, message: Option<&str>) -> Result<()> {
let body = message.unwrap_or("Not Implemented");
self.update_response_body(
body.as_bytes().to_vec(),
"text/plain; charset=utf-8",
Some(StatusCode::NOT_IMPLEMENTED),
);
Ok(())
}
/// Return empty response (204 No Content)
pub fn empty(&mut self) -> Result<()> {
self.update_response_body(Vec::new(), "text/plain", Some(StatusCode::NO_CONTENT));
Ok(())
}
/// Return success response with optional data
pub fn success<T: serde::Serialize>(&mut self, data: Option<T>) -> Result<()> {
let body = match data {
Some(d) => serde_json::to_string(&d)?.into_bytes(),
None => b"{\"success\":true}".to_vec(),
};
self.update_response_body(body, "application/json", None);
Ok(())
}
/// Return plain text response (Total.js style)
pub fn plain(&mut self, text: impl Into<String>) -> Result<()> {
self.update_response_body(text.into().into_bytes(), "text/plain; charset=utf-8", None);
Ok(())
}
/// Return HTML response (Total.js style)
pub fn html(&mut self, content: impl Into<String>) -> Result<()> {
self.update_response_body(
content.into().into_bytes(),
"text/html; charset=utf-8",
None,
);
Ok(())
}
// Total.js-style client information properties
/// Get client IP address (Total.js: controller.ip)
pub fn ip(&self) -> String {
self.req.client_ip()
}
/// Get user agent string (Total.js: controller.ua)
pub fn user_agent(&self) -> Option<&str> {
self.req.user_agent()
}
/// Check if request is from mobile device (Total.js: controller.mobile)
pub fn is_mobile(&self) -> bool {
self.req.is_mobile()
}
/// Check if request is from bot/crawler (Total.js: controller.robot)
pub fn is_robot(&self) -> bool {
self.req.is_robot()
}
/// Check if request is HTTPS (Total.js: controller.secured)
pub fn is_secure(&self) -> bool {
self.req.is_secure()
}
/// Check if request is AJAX/XHR (Total.js: controller.xhr)
pub fn is_xhr(&self) -> bool {
self.req.is_xhr()
}
/// Get preferred language (Total.js: controller.language)
pub fn language(&self) -> Option<&str> {
self.req.language()
}
/// Get HTTP referrer (Total.js: controller.referrer)
pub fn referrer(&self) -> Option<&str> {
self.req.referrer()
}
/// Get full request URL (Total.js: controller.url)
pub fn url(&self) -> &str {
&self.req.uri
}
// Total.js-style file handling methods
/// Get uploaded files (Total.js: controller.files)
pub fn files(&mut self) -> Result<&FileCollection> {
self.req.files()
}
/// Get specific uploaded file by field name
pub fn file(&mut self, field_name: &str) -> Result<Option<&UploadedFile>> {
self.req.file(field_name)
}
/// Send file download response (Total.js: controller.file)
pub async fn file_download<P: AsRef<Path>>(
&mut self,
path: P,
download_name: Option<&str>,
) -> Result<()> {
let new_response = Response::file_download(path, download_name).await?;
self.update_response(new_response);
Ok(())
}
/// Send file download response constrained to a base directory.
pub async fn file_download_from<B: AsRef<Path>, P: AsRef<Path>>(
&mut self,
base_dir: B,
path: P,
download_name: Option<&str>,
) -> Result<()> {
let new_response = Response::file_download_from(base_dir, path, download_name).await?;
self.update_response(new_response);
Ok(())
}
/// Send file for inline viewing
pub async fn file_inline<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
let new_response = Response::file_inline(path).await?;
self.update_response(new_response);
Ok(())
}
/// Send inline file response constrained to a base directory.
pub async fn file_inline_from<B: AsRef<Path>, P: AsRef<Path>>(
&mut self,
base_dir: B,
path: P,
) -> Result<()> {
let new_response = Response::file_inline_from(base_dir, path).await?;
self.update_response(new_response);
Ok(())
}
/// Stream a file download instead of buffering it in memory.
///
/// Same headers and path rules as [`Self::file_download`], but memory
/// stays flat at one 64 KiB chunk however large the file is. Prefer this
/// for anything big enough that holding it in memory once per concurrent
/// request would matter. An I/O error after the first chunk cannot become
/// a 500; the client receives a truncated download.
pub async fn file_download_stream<P: AsRef<Path>>(
&mut self,
path: P,
download_name: Option<&str>,
) -> Result<()> {
let new_response = Response::file_download_stream(path, download_name).await?;
self.update_response(new_response);
Ok(())
}
/// Stream a file download, constrained to a base directory.
pub async fn file_download_stream_from<B: AsRef<Path>, P: AsRef<Path>>(
&mut self,
base_dir: B,
path: P,
download_name: Option<&str>,
) -> Result<()> {
let new_response =
Response::file_download_stream_from(base_dir, path, download_name).await?;
self.update_response(new_response);
Ok(())
}
/// Stream a file for inline display instead of buffering it in memory.
pub async fn file_inline_stream<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
let new_response = Response::file_inline_stream(path).await?;
self.update_response(new_response);
Ok(())
}
/// Stream a file for inline display, constrained to a base directory.
pub async fn file_inline_stream_from<B: AsRef<Path>, P: AsRef<Path>>(
&mut self,
base_dir: B,
path: P,
) -> Result<()> {
let new_response = Response::file_inline_stream_from(base_dir, path).await?;
self.update_response(new_response);
Ok(())
}
/// Send binary data response (Total.js: controller.binary)
pub fn binary(
&mut self,
data: Vec<u8>,
content_type: &str,
download_name: Option<&str>,
) -> Result<()> {
let new_response = Response::binary(data, content_type, download_name);
self.update_response(new_response);
Ok(())
}
/// Send a streaming response (Total.js: controller.stream).
///
/// `body` is anything convertible into a [`Body`](crate::http::Body): a
/// `Vec<u8>` is sent buffered, a `Body::from_stream(..)` is sent chunk by
/// chunk as it is produced. Headers already set on the response (by
/// inbound middleware, say) are preserved, as with every `ctx.*` sender.
///
/// ```rust,no_run
/// use rustf::prelude::*;
/// use bytes::Bytes;
///
/// async fn export(ctx: &mut Context) -> rustf::Result<()> {
/// let rows = futures::stream::iter((1..=3).map(|n| {
/// Ok(Bytes::from(format!("{n},row {n}\n")))
/// }));
/// ctx.stream(Body::from_stream(rows), "text/csv", Some("rows.csv"))
/// }
/// ```
pub fn stream(
&mut self,
body: impl Into<Body>,
content_type: &str,
download_name: Option<&str>,
) -> Result<()> {
let new_response = Response::stream(body, content_type, download_name);
self.update_response(new_response);
Ok(())
}
/// Send a Server-Sent Events stream.
///
/// The response stays open and each [`SseEvent`](crate::http::SseEvent)
/// is pushed to the client as it arrives; it ends when `events` ends.
/// `events` may yield `SseEvent` or `rustf::Result<SseEvent>`; an `Err`
/// aborts the stream. See [`crate::http::sse`] for the wire format and a
/// channel-backed example.
pub fn sse<S>(&mut self, events: S) -> Result<()>
where
S: futures::Stream + Send + 'static,
S::Item: crate::http::sse::SseItem,
{
let new_response = Response::sse(events);
self.update_response(new_response);
Ok(())
}
/// Send a Server-Sent Events stream with idle keep-alive comments.
///
/// Use this when the feed can go quiet for longer than the idle timeout
/// of a proxy in front of the server. See
/// [`crate::http::sse::keep_alive`] for choosing the interval.
pub fn sse_with_keep_alive<S>(
&mut self,
events: S,
keep_alive: std::time::Duration,
) -> Result<()>
where
S: futures::Stream + Send + 'static,
S::Item: crate::http::sse::SseItem,
{
let new_response = Response::sse_with_keep_alive(events, keep_alive);
self.update_response(new_response);
Ok(())
}
/// Set flash success message
pub fn flash_success(&self, message: impl Into<String>) -> Result<()> {
self.flash("success", message.into())
}
/// Set flash error message
pub fn flash_error(&self, message: impl Into<String>) -> Result<()> {
self.flash("error", message.into())
}
/// Set flash info message
pub fn flash_info(&self, message: impl Into<String>) -> Result<()> {
self.flash("info", message.into())
}
/// Set flash warning message
pub fn flash_warning(&self, message: impl Into<String>) -> Result<()> {
self.flash("warning", message.into())
}
/// Clear all flash messages
pub fn flash_clear(&self) -> Result<()> {
let session = self.require_session()?;
session.flash_clear();
Ok(())
}
/// Clear a specific flash message by key
pub fn flash_clear_key(&self, key: &str) -> Result<()> {
let session = self.require_session()?;
session.flash_remove(key);
Ok(())
}
// Source-first query parameter methods (canonical implementation)
/// Get a query parameter as string (returns error if missing).
/// Preferred discoverable name for query parameter access.
pub fn query_str(&self, key: &str) -> Result<String> {
self.req
.query
.get(key)
.filter(|s| !s.is_empty())
.cloned()
.ok_or_else(|| Error::InvalidInput(format!("Query parameter '{}' is required", key)))
}
/// Get a query parameter as integer (returns error if missing or invalid).
/// Preferred discoverable name for query parameter access.
pub fn query_int(&self, key: &str) -> Result<i32> {
self.query_str(key)?.parse().map_err(|_| {
Error::InvalidInput(format!("Query parameter '{}' must be a valid integer", key))
})
}
/// Get a query parameter as boolean (returns error if missing).
/// Preferred discoverable name for query parameter access.
pub fn query_bool(&self, key: &str) -> Result<bool> {
let value = self.query_str(key)?;
Ok(matches!(value.as_str(), "true" | "1" | "yes" | "on"))
}
/// Get a query parameter as string with default value.
/// Preferred discoverable name for query parameter access.
pub fn query_str_or(&self, key: &str, default: &str) -> String {
self.query_str(key).unwrap_or_else(|_| default.to_string())
}
/// Get a query parameter as integer with default value.
/// Preferred discoverable name for query parameter access.
pub fn query_int_or(&self, key: &str, default: i32) -> i32 {
self.query_int(key).unwrap_or(default)
}
/// Get a query parameter as boolean with default value.
/// Preferred discoverable name for query parameter access.
pub fn query_bool_or(&self, key: &str, default: bool) -> bool {
self.query_bool(key).unwrap_or(default)
}
/// Get a query parameter parsed into any `FromStr` type.
///
/// The typed accessor for everything `query_int` and `query_bool` do not
/// cover — `f64`, `i64`, `u32`, `Uuid`, `Decimal`, `NaiveDate`,
/// `DateTime<Utc>`, `IpAddr`. Never hand-write `.parse()` on a query value.
///
/// ```ignore
/// let start: NaiveDate = ctx.query_as("start")?;
/// let radius: f64 = ctx.query_as("radius")?;
/// ```
pub fn query_as<T: std::str::FromStr>(&self, key: &str) -> Result<T> {
let value = self.query_str(key)?;
value.trim().parse::<T>().map_err(|_| {
Error::InvalidInput(format!(
"Query parameter '{}' must be a valid {}",
key,
short_type_name::<T>()
))
})
}
/// Get a query parameter parsed into any `FromStr` type, or a default if
/// the parameter is missing, empty or unparseable.
pub fn query_as_or<T: std::str::FromStr>(&self, key: &str, default: T) -> T {
self.query_as(key).unwrap_or(default)
}
// Source-first route parameter methods (canonical implementation)
/// Get a route parameter as string (returns error if missing).
/// Preferred discoverable name for route parameter access.
pub fn param_str(&self, key: &str) -> Result<String> {
self.req
.params
.get(key)
.filter(|s| !s.is_empty())
.cloned()
.ok_or_else(|| Error::InvalidInput(format!("Route parameter '{}' is required", key)))
}
/// Get a route parameter as integer (returns error if missing or invalid).
/// Preferred discoverable name for route parameter access.
pub fn param_int(&self, key: &str) -> Result<i32> {
self.param_str(key)?.parse().map_err(|_| {
Error::InvalidInput(format!("Route parameter '{}' must be a valid integer", key))
})
}
/// Get a route parameter as string with default value.
/// Preferred discoverable name for route parameter access.
pub fn param_str_or(&self, key: &str, default: &str) -> String {
self.param_str(key).unwrap_or_else(|_| default.to_string())
}
/// Get a route parameter as integer with default value.
/// Preferred discoverable name for route parameter access.
pub fn param_int_or(&self, key: &str, default: i32) -> i32 {
self.param_int(key).unwrap_or(default)
}
/// Get a route parameter parsed into any `FromStr` type.
///
/// The typed accessor for everything `param_int` does not cover — `i64`,
/// `u32`, `Uuid`, `NaiveDate`, `IpAddr`. Never hand-write `.parse()` on a
/// route parameter.
///
/// ```ignore
/// let id: i64 = ctx.param_as("id")?;
/// let uuid: Uuid = ctx.param_as("uuid")?;
/// ```
pub fn param_as<T: std::str::FromStr>(&self, key: &str) -> Result<T> {
let value = self.param_str(key)?;
value.trim().parse::<T>().map_err(|_| {
Error::InvalidInput(format!(
"Route parameter '{}' must be a valid {}",
key,
short_type_name::<T>()
))
})
}
/// Get a route parameter parsed into any `FromStr` type, or a default if
/// the parameter is missing, empty or unparseable.
pub fn param_as_or<T: std::str::FromStr>(&self, key: &str, default: T) -> T {
self.param_as(key).unwrap_or(default)
}
/// Get request body as JSON
pub fn body_json<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
self.req.body_as_json()
}
/// Get request body as form data (cached to avoid re-parsing).
///
/// Returns a [`FormData`] wrapper with typed getters: `form.get_int("id")?`,
/// `form.get_str("name")?`, `form.get_as::<f64>("price")?`. Multi-value
/// fields keep every value — `form.get_all("tags")`.
pub fn body_form(&mut self) -> Result<FormData> {
Ok(FormData::new(self.body_form_data()?.clone()))
}
/// Get request body as form data with array support (field[] syntax)
/// Returns a reference to cached data to avoid cloning overhead
pub fn body_form_data(&mut self) -> Result<&HashMap<String, FormValue>> {
if self.cached_form_data_arrays.is_none() {
self.cached_form_data_arrays = Some(self.req.body_as_form_data());
}
match self.cached_form_data_arrays.as_ref().unwrap() {
Ok(data) => Ok(data),
Err(e) => Err(Error::InvalidInput(e.to_string())),
}
}
/// Parse the form body into a typed structure.
///
/// Fields are parsed out of their string form, so `f64`, `i64`, `bool`,
/// `Option<T>` and `Vec<T>` all work; a multi-value field (`tags[]`)
/// deserializes into a sequence field.
///
/// ```ignore
/// #[derive(Deserialize)]
/// struct NewProduct {
/// name: String,
/// price: f64,
/// tags: Vec<String>,
/// }
/// let product: NewProduct = ctx.body_form_typed()?;
/// ```
pub fn body_form_typed<T: DeserializeOwned>(&mut self) -> Result<T> {
let form_data = self.body_form_data()?;
crate::http::form_de::from_form_data(form_data)
}
// Source-first body field methods (canonical implementation)
/// Get a field from body as string (returns error if missing).
/// Preferred discoverable name for body field access.
pub fn body_str(&mut self, key: &str) -> Result<String> {
self.body_form_data()?
.get(key)
.map(|v| v.as_string())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.ok_or_else(|| Error::InvalidInput(format!("Field '{}' is required", key)))
}
/// Get a field from body as integer (returns error if missing or invalid).
/// Preferred discoverable name for body field access.
pub fn body_int(&mut self, key: &str) -> Result<i32> {
self.body_str(key)?
.parse()
.map_err(|_| Error::InvalidInput(format!("Field '{}' must be a valid integer", key)))
}
/// Get a field from body as boolean (returns error if missing).
/// Preferred discoverable name for body field access.
pub fn body_bool(&mut self, key: &str) -> Result<bool> {
let value = self.body_str(key)?;
Ok(matches!(
value.as_str(),
"true" | "1" | "yes" | "on" | "checked"
))
}
/// Get a field from body as string with default value.
/// Preferred discoverable name for body field access.
pub fn body_str_or(&mut self, key: &str, default: &str) -> String {
self.body_str(key).unwrap_or_else(|_| default.to_string())
}
/// Get a field from body as integer with default value.
/// Preferred discoverable name for body field access.
pub fn body_int_or(&mut self, key: &str, default: i32) -> i32 {
self.body_int(key).unwrap_or(default)
}
/// Get a field from body as boolean with default value.
/// Preferred discoverable name for body field access.
pub fn body_bool_or(&mut self, key: &str, default: bool) -> bool {
self.body_bool(key).unwrap_or(default)
}
/// Get a body field parsed into any `FromStr` type.
///
/// The typed accessor for everything `body_int` and `body_bool` do not
/// cover — `f64`, `i64`, `Uuid`, `Decimal`, `NaiveDate`. Never hand-write
/// `.parse()` on a body field.
///
/// ```ignore
/// let price: f64 = ctx.body_as("price")?;
/// let due: NaiveDate = ctx.body_as("due_date")?;
/// ```
pub fn body_as<T: std::str::FromStr>(&mut self, key: &str) -> Result<T> {
let value = self.body_str(key)?;
value.trim().parse::<T>().map_err(|_| {
Error::InvalidInput(format!(
"Field '{}' must be a valid {}",
key,
short_type_name::<T>()
))
})
}
/// Get a body field parsed into any `FromStr` type, or a default if the
/// field is missing, empty or unparseable.
pub fn body_as_or<T: std::str::FromStr>(&mut self, key: &str, default: T) -> T {
self.body_as(key).unwrap_or(default)
}
/// Get the full body data as JSON (converts form data to JSON if needed)
/// This provides a unified interface regardless of content type
pub fn full_body(&mut self) -> Result<serde_json::Value> {
let content_type = self
.req
.headers
.get("content-type")
.map(|s| s.as_str())
.unwrap_or("");
if content_type.contains("application/json") {
// Already JSON, return as-is
self.body_json::<serde_json::Value>()
} else if content_type.contains("application/x-www-form-urlencoded")
|| content_type.contains("multipart/form-data")
{
// Convert form data to JSON
let form_data = self.body_form_data()?;
Ok(Self::form_to_json(form_data))
} else {
let text = self.req.body_as_string();
if text.is_empty() {
Ok(serde_json::Value::Null)
} else {
Ok(serde_json::Value::String(text))
}
}
}
/// Get the raw body as string (for text, XML, or other content types)
pub fn raw_body(&self) -> String {
self.req.body_as_string()
}
/// Helper function to convert form data to JSON
fn form_to_json(form_data: &HashMap<String, FormValue>) -> serde_json::Value {
let mut json_map = serde_json::Map::new();
for (key, value) in form_data {
let json_value = match value {
FormValue::Single(s) => {
// Try to parse as number or boolean, fallback to string
if let Ok(n) = s.parse::<i64>() {
serde_json::Value::Number(n.into())
} else if let Ok(f) = s.parse::<f64>() {
serde_json::Number::from_f64(f)
.map(serde_json::Value::Number)
.unwrap_or_else(|| serde_json::Value::String(s.clone()))
} else if s == "true" || s == "false" {
serde_json::Value::Bool(s == "true")
} else {
serde_json::Value::String(s.clone())
}
}
FormValue::Multiple(arr) => {
let values: Vec<serde_json::Value> = arr
.iter()
.map(|s| {
// Try to parse each value
if let Ok(n) = s.parse::<i64>() {
serde_json::Value::Number(n.into())
} else if let Ok(f) = s.parse::<f64>() {
serde_json::Number::from_f64(f)
.map(serde_json::Value::Number)
.unwrap_or_else(|| serde_json::Value::String(s.clone()))
} else if s == "true" || s == "false" {
serde_json::Value::Bool(s == "true")
} else {
serde_json::Value::String(s.clone())
}
})
.collect();
serde_json::Value::Array(values)
}
};
json_map.insert(key.clone(), json_value);
}
serde_json::Value::Object(json_map)
}
/// Get a header value
pub fn header(&self, name: &str) -> Option<&str> {
let normalized = name.to_ascii_lowercase();
self.req.headers.get(&normalized).map(|s| s.as_str())
}
/// Add a header to the response
pub fn add_header(&mut self, name: impl Into<String>, value: impl Into<String>) {
if let Some(response) = self.res.as_mut() {
let name = name.into();
let value = value.into();
response.add_header(&name, &value);
}
}
/// Set the response status code
pub fn status(&mut self, status: hyper::StatusCode) {
if let Some(response) = self.res.as_mut() {
response.status = status;
}
}
/// Return JSON response
pub fn json<T: serde::Serialize>(&mut self, data: T) -> Result<()> {
let json_string = serde_json::to_string(&data)?;
self.update_response_body(json_string.into_bytes(), "application/json", None);
Ok(())
}
/// Session convenience methods
pub fn session_set<T: serde::Serialize>(&self, key: &str, value: T) -> Result<()> {
let session = self.require_session()?;
session.set(key, value)
}
pub fn session_get<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.session()?.get(key)
}
/// Clear all session data and flash messages
///
/// This removes all data from the session but keeps the session ID intact.
/// Useful for user logout where you want to clear data but maintain session tracking.
pub fn session_clear(&self) {
if let Some(session) = self.session() {
session.clear();
}
}
/// Flush all session data (alias for session_clear)
///
/// Provides Laravel-style compatibility for developers familiar with flush().
pub fn session_flush(&self) {
self.session_clear();
}
/// Mark session for destruction (clears all data)
///
/// This clears all session data locally. For complete session destruction
/// including removal from storage, the SessionStore would need to handle
/// the actual storage deletion.
pub fn session_destroy(&self) {
if let Some(session) = self.session() {
session.destroy();
}
self.session_destroyed.store(true, Ordering::Relaxed);
}
/// Whether the current session should be destroyed in the outbound phase.
pub fn is_session_destroyed(&self) -> bool {
self.session_destroyed.load(Ordering::Relaxed)
}
pub fn session_remove(&self, key: &str) -> Option<Value> {
self.session()?.remove(key)
}
// Total.js compatibility convenience methods
/// Get cookie value by name (Total.js: controller.cookie)
pub fn cookie(&self, name: &str) -> Option<String> {
self.req.cookie(name)
}
/// Get host from Host header (Total.js: controller.host)
pub fn host(&self) -> Option<&str> {
self.req.host()
}
/// Get hostname with optional path (Total.js: controller.hostname)
pub fn hostname(&self, path: Option<&str>) -> String {
self.req.hostname(path)
}
/// Get request path from URI (Total.js: controller.path)
pub fn path(&self) -> &str {
self.req.path()
}
/// Get file extension from path (Total.js: controller.extension)
pub fn extension(&self) -> Option<&str> {
self.req.extension()
}
/// Check if request is authorized (Total.js: controller.isAuthorized)
pub fn is_authorized(&self) -> bool {
self.req.is_authorized()
}
/// Get authorization header (Total.js: controller.authorization)
pub fn authorization(&self) -> Option<&str> {
self.req.authorization()
}
/// Check if request is from a proxy (Total.js: controller.isProxy)
pub fn is_proxy(&self) -> bool {
self.req.is_proxy()
}
/// Check if request is for a static file (Total.js: controller.isStaticFile)
pub fn is_static_file(&self) -> bool {
self.req.is_static_file()
}
/// Get subdomain from host (Total.js: controller.subdomain)
pub fn subdomain(&self) -> Option<String> {
self.req.subdomain()
}
/// Get path segments as array (Total.js: controller.split)
pub fn split(&self) -> Vec<&str> {
self.req.split()
}
/// Verify CSRF token for the current request (one-time use)
pub fn verify_csrf(&mut self, token_id: Option<&str>) -> Result<bool> {
let token_id = token_id.unwrap_or("_csrf_token");
// Get submitted token from request first (needs mutable self)
let submitted_token = self.get_submitted_csrf_token_with_id(token_id);
// Require session for CSRF
let session = match self.session() {
Some(s) => s,
None => return Ok(false),
};
// Get stored token data from session
let token_data: Option<serde_json::Value> = session.get(token_id);
let token_data = match token_data {
Some(data) => data,
None => return Ok(false),
};
// Extract token and expiration
let stored_token = token_data.get("token").and_then(|v| v.as_str());
let valid_to = token_data.get("valid_to").and_then(|v| v.as_u64());
if stored_token.is_none() || valid_to.is_none() {
return Ok(false);
}
// Check expiration
use std::time::{SystemTime, UNIX_EPOCH};
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| Error::internal(format!("System time error: {}", e)))?
.as_secs();
if now > valid_to.unwrap() {
// Token expired, remove it
let _ = session.remove(token_id);
return Ok(false);
}
let valid = match submitted_token {
Some(submitted) => {
// Constant-time comparison to prevent timing attacks
constant_time_eq(stored_token.unwrap().as_bytes(), submitted.as_bytes())
}
None => false,
};
// IMPORTANT: Destroy token after verification (one-time use)
if valid {
let _ = session.remove(token_id);
}
Ok(valid)
}
/// Generate CSRF token with optional ID and expiration
pub fn generate_csrf(&self, token_id: Option<&str>) -> Result<String> {
let token_id = token_id.unwrap_or("_csrf_token");
let token = Request::generate_csrf_token();
// Require session for CSRF
let session = self.require_session()?;
// Store token with expiration timestamp (1 hour validity)
use std::time::{SystemTime, UNIX_EPOCH};
let valid_to = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| Error::internal(format!("System time error: {}", e)))?
.as_secs()
+ 3600; // 1 hour validity
// Store as JSON object with token and expiration
let token_data = serde_json::json!({
"token": token,
"valid_to": valid_to
});
session.set(token_id, token_data)?;
Ok(token)
}
/// Get submitted CSRF token from request with custom token ID support
fn get_submitted_csrf_token_with_id(&mut self, token_id: &str) -> Option<String> {
// Try X-CSRF-Token header first
if let Some(token) = self.req.headers.get("x-csrf-token") {
return Some(token.clone());
}
// Try form data if POST request (uses cached form data)
if matches!(
self.req.method.as_str(),
"POST" | "PUT" | "PATCH" | "DELETE"
) {
if let Ok(form_data) = self.body_form() {
// Try token_id field
if let Some(token) = form_data.get(token_id) {
return Some(token.to_string());
}
// Try _token field for default
if token_id == "_csrf_token" {
if let Some(token) = form_data.get("_token") {
return Some(token.to_string());
}
}
}
}
None
}
}
/// Constant-time comparison to prevent timing attacks
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut result = 0u8;
for (x, y) in a.iter().zip(b.iter()) {
result |= x ^ y;
}
result == 0
}
#[cfg(test)]
mod tests {
use super::*;
use crate::session::Session;
fn create_test_context() -> Context {
let mut request = Request::new("GET", "/test", "1.1");
request.query.insert("page".to_string(), "2".to_string());
request
.query
.insert("active".to_string(), "true".to_string());
request
.query
.insert("search".to_string(), "rust".to_string());
request.params.insert("id".to_string(), "123".to_string());
request
.params
.insert("slug".to_string(), "test-post".to_string());
let views = Arc::new(ViewEngine::new());
Context::new(request, views)
}
#[test]
fn test_require_session_and_auth_return_401_errors() {
let ctx = create_test_context();
let err = ctx.require_session().err().unwrap();
assert_eq!(err.status_code(), 401);
let err = ctx.require_auth().err().unwrap();
assert_eq!(err.status_code(), 401);
let mut ctx = create_test_context();
ctx.set_session(Some(Arc::new(Session::new("sess-1"))));
let err = ctx.require_auth().err().unwrap();
assert_eq!(err.status_code(), 401);
}
#[test]
fn test_logout_marks_session_for_destruction() {
let mut ctx = create_test_context();
ctx.set_session(Some(Arc::new(Session::new("sess-1"))));
ctx.logout().unwrap();
assert!(ctx.is_session_destroyed());
assert!(ctx.session().unwrap().is_destroyed());
}
#[test]
fn test_csrf_verification_rejects_query_tokens() {
let mut ctx = create_test_context();
ctx.set_session(Some(Arc::new(Session::new("sess-1"))));
let token = ctx.generate_csrf(None).unwrap();
ctx.req.method = "POST".to_string();
ctx.req
.query
.insert("_csrf_token".to_string(), token.clone());
assert!(!ctx.verify_csrf(None).unwrap());
}
#[test]
fn test_header_lookup_is_case_insensitive() {
let mut request = Request::new("GET", "/test", "1.1");
request
.headers
.insert("content-type".to_string(), "application/json".to_string());
let views = Arc::new(ViewEngine::new());
let ctx = Context::new(request, views);
assert_eq!(ctx.header("Content-Type"), Some("application/json"));
assert_eq!(ctx.header("content-type"), Some("application/json"));
}
#[test]
fn test_redirect_replaces_stale_content_headers() {
let mut ctx = create_test_context();
ctx.plain("hello").unwrap();
ctx.add_header("X-Test", "keep");
ctx.redirect("/next").unwrap();
let response = ctx.get_response().unwrap();
assert_eq!(response.status, StatusCode::FOUND);
assert!(response
.headers
.iter()
.any(|(k, v)| k == "Location" && v == "/next"));
assert!(response
.headers
.iter()
.any(|(k, v)| k == "X-Test" && v == "keep"));
assert!(!response
.headers
.iter()
.any(|(k, _)| k.eq_ignore_ascii_case("Content-Type")));
}
#[test]
fn test_query_methods() {
let ctx = create_test_context();
// Test mandatory query methods
assert_eq!(ctx.query_str("page").unwrap(), "2");
assert_eq!(ctx.query_int("page").unwrap(), 2);
assert_eq!(ctx.query_bool("active").unwrap(), true);
// Test missing required query param
assert!(ctx.query_str("missing").is_err());
assert!(ctx.query_int("missing").is_err());
// Test optional query methods
assert_eq!(ctx.query_str_or("page", "1"), "2");
assert_eq!(ctx.query_int_or("page", 1), 2);
assert_eq!(ctx.query_bool_or("active", false), true);
// Test defaults for missing params
assert_eq!(ctx.query_str_or("missing", "default"), "default");
assert_eq!(ctx.query_int_or("missing", 99), 99);
assert_eq!(ctx.query_bool_or("missing", true), true);
}
#[test]
fn test_query_as_parses_types_the_int_and_bool_accessors_do_not_cover() {
let mut request = Request::new("GET", "/test", "1.1");
request
.query
.insert("radius".to_string(), "12.5".to_string());
request
.query
.insert("start".to_string(), "2026-09-04".to_string());
request
.query
.insert("big".to_string(), "9000000000".to_string());
request
.query
.insert("bad".to_string(), "twelve".to_string());
let ctx = Context::new(request, Arc::new(ViewEngine::new()));
assert_eq!(ctx.query_as::<f64>("radius").unwrap(), 12.5);
assert_eq!(ctx.query_as::<i64>("big").unwrap(), 9_000_000_000);
assert!(
ctx.query_as::<std::net::IpAddr>("missing").is_err(),
"a missing parameter is an error, not a default"
);
// The error names the parameter and the expected type, without the
// module path serde would otherwise print.
let error = ctx.query_as::<f64>("bad").unwrap_err().to_string();
assert!(
error.contains("bad") && error.contains("f64"),
"unhelpful error: {}",
error
);
assert_eq!(ctx.query_as_or::<f64>("radius", 1.0), 12.5);
assert_eq!(ctx.query_as_or::<f64>("bad", 1.0), 1.0);
assert_eq!(ctx.query_as_or::<f64>("missing", 1.0), 1.0);
}
#[test]
fn test_param_as_parses_types_the_int_accessor_does_not_cover() {
let ctx = create_test_context();
assert_eq!(ctx.param_as::<i64>("id").unwrap(), 123);
assert_eq!(ctx.param_as::<u32>("id").unwrap(), 123);
assert!(ctx.param_as::<i64>("slug").is_err());
assert!(ctx.param_as::<i64>("missing").is_err());
assert_eq!(ctx.param_as_or::<i64>("id", 0), 123);
assert_eq!(ctx.param_as_or::<i64>("slug", -1), -1);
}
#[test]
fn test_body_as_parses_form_fields_into_any_from_str_type() {
let mut request = Request::new("POST", "/test", "1.1");
request.headers.insert(
"content-type".to_string(),
"application/x-www-form-urlencoded".to_string(),
);
request.set_body(b"price=19.99&qty=7&label=widget".to_vec());
let mut ctx = Context::new(request, Arc::new(ViewEngine::new()));
assert_eq!(ctx.body_as::<f64>("price").unwrap(), 19.99);
assert_eq!(ctx.body_as::<i64>("qty").unwrap(), 7);
assert!(ctx.body_as::<f64>("label").is_err());
assert_eq!(ctx.body_as_or::<f64>("label", 0.0), 0.0);
assert_eq!(ctx.body_as_or::<f64>("missing", 2.5), 2.5);
}
#[test]
fn test_body_form_keeps_every_value_of_a_repeated_field() {
let mut request = Request::new("POST", "/test", "1.1");
request.headers.insert(
"content-type".to_string(),
"application/x-www-form-urlencoded".to_string(),
);
request.set_body(b"title=Hello&tags[]=rust&tags[]=web".to_vec());
let mut ctx = Context::new(request, Arc::new(ViewEngine::new()));
let form = ctx.body_form().unwrap();
assert_eq!(form.get("title"), Some("Hello"));
assert_eq!(form.get_all("tags"), vec!["rust", "web"]);
}
#[test]
fn test_body_form_typed_parses_non_string_fields() {
#[derive(serde::Deserialize)]
struct NewProduct {
name: String,
price: f64,
quantity: i64,
in_stock: bool,
note: Option<String>,
tags: Vec<String>,
}
let mut request = Request::new("POST", "/test", "1.1");
request.headers.insert(
"content-type".to_string(),
"application/x-www-form-urlencoded".to_string(),
);
request.set_body(
b"name=Widget&price=19.99&quantity=42&in_stock=on¬e=&tags[]=new&tags[]=sale"
.to_vec(),
);
let mut ctx = Context::new(request, Arc::new(ViewEngine::new()));
let product: NewProduct = ctx.body_form_typed().unwrap();
assert_eq!(product.name, "Widget");
// The old JSON-of-strings bridge failed here with "invalid type: string".
assert_eq!(product.price, 19.99);
assert_eq!(product.quantity, 42);
assert!(product.in_stock);
assert_eq!(product.note, None);
assert_eq!(product.tags, vec!["new".to_string(), "sale".to_string()]);
}
#[test]
fn test_param_methods() {
let ctx = create_test_context();
// Test mandatory param methods
assert_eq!(ctx.param_str("id").unwrap(), "123");
assert_eq!(ctx.param_int("id").unwrap(), 123);
assert_eq!(ctx.param_str("slug").unwrap(), "test-post");
// Test missing required param
assert!(ctx.param_str("missing").is_err());
assert!(ctx.param_int("missing").is_err());
// Test optional param methods
assert_eq!(ctx.param_str_or("id", "0"), "123");
assert_eq!(ctx.param_int_or("id", 0), 123);
assert_eq!(ctx.param_str_or("missing", "default"), "default");
assert_eq!(ctx.param_int_or("missing", 42), 42);
}
#[test]
fn test_bool_parsing() {
let mut request = Request::new("GET", "/test", "1.1");
request.query.insert("yes".to_string(), "yes".to_string());
request.query.insert("one".to_string(), "1".to_string());
request.query.insert("on".to_string(), "on".to_string());
request.query.insert("true".to_string(), "true".to_string());
request
.query
.insert("false".to_string(), "false".to_string());
request.query.insert("zero".to_string(), "0".to_string());
let views = Arc::new(ViewEngine::new());
let ctx = Context::new(request, views);
assert_eq!(ctx.query_bool("yes").unwrap(), true);
assert_eq!(ctx.query_bool("one").unwrap(), true);
assert_eq!(ctx.query_bool("on").unwrap(), true);
assert_eq!(ctx.query_bool("true").unwrap(), true);
assert_eq!(ctx.query_bool("false").unwrap(), false);
assert_eq!(ctx.query_bool("zero").unwrap(), false);
}
#[test]
fn test_error_messages() {
let ctx = create_test_context();
// Check error messages
let err = ctx.query_str("missing").unwrap_err();
assert!(err
.to_string()
.contains("Query parameter 'missing' is required"));
let err = ctx.param_int("slug").unwrap_err();
assert!(err
.to_string()
.contains("Route parameter 'slug' must be a valid integer"));
}
#[test]
fn test_source_first_query_methods() {
let ctx = create_test_context();
// Test source-first query methods (canonical API)
assert_eq!(ctx.query_str("page").unwrap(), "2");
assert_eq!(ctx.query_int("page").unwrap(), 2);
assert_eq!(ctx.query_bool("active").unwrap(), true);
// Test missing required query param
assert!(ctx.query_str("missing").is_err());
assert!(ctx.query_int("missing").is_err());
// Test optional query methods
assert_eq!(ctx.query_str_or("page", "1"), "2");
assert_eq!(ctx.query_int_or("page", 1), 2);
assert_eq!(ctx.query_bool_or("active", false), true);
// Test defaults for missing params
assert_eq!(ctx.query_str_or("missing", "default"), "default");
assert_eq!(ctx.query_int_or("missing", 99), 99);
assert_eq!(ctx.query_bool_or("missing", true), true);
}
#[test]
fn test_source_first_param_methods() {
let ctx = create_test_context();
// Test source-first param methods (canonical API)
assert_eq!(ctx.param_str("id").unwrap(), "123");
assert_eq!(ctx.param_int("id").unwrap(), 123);
assert_eq!(ctx.param_str("slug").unwrap(), "test-post");
// Test missing required param
assert!(ctx.param_str("missing").is_err());
assert!(ctx.param_int("missing").is_err());
// Test optional param methods
assert_eq!(ctx.param_str_or("id", "0"), "123");
assert_eq!(ctx.param_int_or("id", 0), 123);
assert_eq!(ctx.param_str_or("missing", "default"), "default");
assert_eq!(ctx.param_int_or("missing", 42), 42);
}
#[test]
fn test_source_first_body_methods() {
let mut request = Request::new("POST", "/test", "1.1");
request.headers.insert(
"content-type".to_string(),
"application/x-www-form-urlencoded".to_string(),
);
let form_data = "name=Alice&age=30&active=true";
request.set_body(form_data.as_bytes().to_vec());
let views = Arc::new(ViewEngine::new());
let mut ctx = Context::new(request, views);
// Test source-first body methods (canonical API)
assert_eq!(ctx.body_str("name").unwrap(), "Alice");
assert_eq!(ctx.body_int("age").unwrap(), 30);
assert_eq!(ctx.body_bool("active").unwrap(), true);
// Test missing required body field
assert!(ctx.body_str("missing").is_err());
assert!(ctx.body_int("missing").is_err());
// Test optional body methods
assert_eq!(ctx.body_str_or("name", "Bob"), "Alice");
assert_eq!(ctx.body_int_or("age", 0), 30);
assert_eq!(ctx.body_bool_or("active", false), true);
assert_eq!(ctx.body_str_or("missing", "default"), "default");
assert_eq!(ctx.body_int_or("missing", 99), 99);
assert_eq!(ctx.body_bool_or("missing", true), true);
}
#[test]
fn test_full_body_with_form_data() {
let mut request = Request::new("POST", "/test", "1.1");
request.headers.insert(
"content-type".to_string(),
"application/x-www-form-urlencoded".to_string(),
);
// Simulate form data
let form_data = "name=John+Doe&age=30&active=true&tags[]=rust&tags[]=web";
request.set_body(form_data.as_bytes().to_vec());
let views = Arc::new(ViewEngine::new());
let mut ctx = Context::new(request, views);
// Get full body as JSON
let json = ctx.full_body().unwrap();
// Check conversion to JSON
assert_eq!(json["name"], "John Doe");
assert_eq!(json["age"], 30);
assert_eq!(json["active"], true);
// Check if tags exists and is an array (brackets are removed during parsing)
assert!(json["tags"].is_array());
let tags = json["tags"].as_array().unwrap();
assert_eq!(tags.len(), 2);
assert_eq!(tags[0], "rust");
assert_eq!(tags[1], "web");
}
#[test]
fn test_full_body_with_json() {
let mut request = Request::new("POST", "/test", "1.1");
request
.headers
.insert("content-type".to_string(), "application/json".to_string());
let json_data = r#"{"name":"Jane Doe","age":25,"active":false}"#;
request.set_body(json_data.as_bytes().to_vec());
let views = Arc::new(ViewEngine::new());
let mut ctx = Context::new(request, views);
// Get full body as JSON
let json = ctx.full_body().unwrap();
assert_eq!(json["name"], "Jane Doe");
assert_eq!(json["age"], 25);
assert_eq!(json["active"], false);
}
#[test]
fn test_full_body_with_text() {
let mut request = Request::new("POST", "/test", "1.1");
request
.headers
.insert("content-type".to_string(), "text/plain".to_string());
let text_data = "Plain text content";
request.set_body(text_data.as_bytes().to_vec());
let views = Arc::new(ViewEngine::new());
let mut ctx = Context::new(request, views);
// Get full body - should wrap text in JSON string
let json = ctx.full_body().unwrap();
assert_eq!(
json,
serde_json::Value::String("Plain text content".to_string())
);
}
#[test]
fn test_full_body_with_json_text() {
let mut request = Request::new("POST", "/test", "1.1");
request
.headers
.insert("content-type".to_string(), "text/plain".to_string());
// Text that happens to be valid JSON
let json_text = r#"{"key": "value"}"#;
request.set_body(json_text.as_bytes().to_vec());
let views = Arc::new(ViewEngine::new());
let mut ctx = Context::new(request, views);
// Non-JSON content types stay as strings even if the payload looks like JSON.
let json = ctx.full_body().unwrap();
assert_eq!(json, serde_json::Value::String(json_text.to_string()));
}
#[test]
fn test_raw_body() {
let mut request = Request::new("POST", "/test", "1.1");
request
.headers
.insert("content-type".to_string(), "text/xml".to_string());
let xml_data = "<root><item>Test</item></root>";
request.set_body(xml_data.as_bytes().to_vec());
let views = Arc::new(ViewEngine::new());
let ctx = Context::new(request, views);
// Get raw body
let raw = ctx.raw_body();
assert_eq!(raw, xml_data);
}
#[test]
fn test_form_to_json_conversion() {
let mut form_data = HashMap::new();
form_data.insert("string".to_string(), FormValue::Single("text".to_string()));
form_data.insert("number".to_string(), FormValue::Single("42".to_string()));
form_data.insert("float".to_string(), FormValue::Single("3.14".to_string()));
form_data.insert(
"bool_true".to_string(),
FormValue::Single("true".to_string()),
);
form_data.insert(
"bool_false".to_string(),
FormValue::Single("false".to_string()),
);
form_data.insert(
"array".to_string(),
FormValue::Multiple(vec!["1".to_string(), "2".to_string(), "3".to_string()]),
);
let json = Context::form_to_json(&form_data);
assert_eq!(json["string"], "text");
assert_eq!(json["number"], 42);
assert_eq!(json["float"], 3.14);
assert_eq!(json["bool_true"], true);
assert_eq!(json["bool_false"], false);
let array = json["array"].as_array().unwrap();
assert_eq!(array.len(), 3);
assert_eq!(array[0], 1);
assert_eq!(array[1], 2);
assert_eq!(array[2], 3);
}
}