FormData.vala 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. using Astralis;
  2. using Invercargill;
  3. using Invercargill.DataStructures;
  4. /**
  5. * FormData Example
  6. *
  7. * Demonstrates handling POST form data in Astralis using async RouteHandler.
  8. * Shows both application/x-www-form-urlencoded and multipart/form-data handling.
  9. */
  10. // HTML form page handler
  11. class FormPageHandler : Object, RouteHandler {
  12. public async HttpResult handle_route(HttpContext context, RouteContext route_context) throws Error {
  13. return new HttpStringResult("""<!DOCTYPE html>
  14. <html>
  15. <head>
  16. <title>Form Data Example</title>
  17. <style>
  18. body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px; }
  19. h1 { color: #333; }
  20. .form-section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
  21. label { display: block; margin: 10px 0 5px; font-weight: bold; }
  22. input, textarea, select { width: 100%; padding: 8px; margin: 5px 0; box-sizing: border-box; }
  23. button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; }
  24. button:hover { background: #0056b3; }
  25. a { color: #007bff; text-decoration: none; }
  26. a:hover { text-decoration: underline; }
  27. </style>
  28. </head>
  29. <body>
  30. <h1>Form Data Examples</h1>
  31. <div class="form-section">
  32. <h2>Simple Form (URL Encoded)</h2>
  33. <form action="/submit-simple" method="POST">
  34. <label for="name">Name:</label>
  35. <input type="text" id="name" name="name" required>
  36. <label for="email">Email:</label>
  37. <input type="email" id="email" name="email" required>
  38. <button type="submit">Submit</button>
  39. </form>
  40. </div>
  41. <div class="form-section">
  42. <h2>Registration Form (URL Encoded)</h2>
  43. <form action="/submit-register" method="POST">
  44. <label for="username">Username:</label>
  45. <input type="text" id="username" name="username" required>
  46. <label for="password">Password:</label>
  47. <input type="password" id="password" name="password" required>
  48. <label for="age">Age:</label>
  49. <input type="number" id="age" name="age" min="18" max="120">
  50. <label for="country">Country:</label>
  51. <select id="country" name="country">
  52. <option value="us">United States</option>
  53. <option value="uk">United Kingdom</option>
  54. <option value="nz">New Zealand</option>
  55. <option value="au">Australia</option>
  56. </select>
  57. <label for="bio">Bio:</label>
  58. <textarea id="bio" name="bio" rows="4"></textarea>
  59. <label>
  60. <input type="checkbox" name="newsletter" value="yes"> Subscribe to newsletter
  61. </label>
  62. <button type="submit">Register</button>
  63. </form>
  64. </div>
  65. <div class="form-section">
  66. <h2>Search Form (URL Encoded)</h2>
  67. <form action="/submit-search" method="POST">
  68. <label for="query">Search Query:</label>
  69. <input type="text" id="query" name="query" required>
  70. <label for="category">Category:</label>
  71. <select id="category" name="category">
  72. <option value="">All Categories</option>
  73. <option value="books">Books</option>
  74. <option value="electronics">Electronics</option>
  75. <option value="clothing">Clothing</option>
  76. </select>
  77. <label for="min_price">Min Price:</label>
  78. <input type="number" id="min_price" name="min_price" min="0" step="0.01">
  79. <label for="max_price">Max Price:</label>
  80. <input type="number" id="max_price" name="max_price" min="0" step="0.01">
  81. <button type="submit">Search</button>
  82. </form>
  83. </div>
  84. <div class="form-section">
  85. <h2>File Upload (Multipart)</h2>
  86. <form action="/submit-file" method="POST" enctype="multipart/form-data">
  87. <label for="description">Description:</label>
  88. <input type="text" id="description" name="description">
  89. <label for="file">File:</label>
  90. <input type="file" id="file" name="file">
  91. <button type="submit">Upload</button>
  92. </form>
  93. </div>
  94. <div class="form-section">
  95. <h2>Links</h2>
  96. <p><a href="/form-debug">Form Debug Tool</a></p>
  97. </div>
  98. </body>
  99. </html>""")
  100. .set_header("Content-Type", "text/html");
  101. }
  102. }
  103. // Simple form submission handler
  104. class SimpleFormHandler : Object, RouteHandler {
  105. public async HttpResult handle_route(HttpContext context, RouteContext route_context) throws Error {
  106. if (!context.request.is_post()) {
  107. return new HttpStringResult("Please use POST method");
  108. }
  109. // Parse form data asynchronously from the request body
  110. FormData form_data = yield FormDataParser.parse(
  111. context.request.request_body,
  112. context.request.content_type
  113. );
  114. var name = form_data.get_field_or_default("name", "Anonymous");
  115. var email = form_data.get_field_or_default("email", "no-email@example.com");
  116. var parts = new Series<string>();
  117. parts.add("Form Submission Received!\n");
  118. parts.add("=========================\n\n");
  119. parts.add(@"Name: $name\n");
  120. parts.add(@"Email: $email\n");
  121. parts.add("\nAll form data:\n");
  122. form_data.fields.to_immutable_buffer()
  123. .iterate((grouping) => {
  124. grouping.iterate((value) => {
  125. parts.add(@" $(grouping.key): $value\n");
  126. });
  127. });
  128. var result = parts.to_immutable_buffer()
  129. .aggregate<string>("", (acc, s) => acc + s);
  130. return new HttpStringResult(result);
  131. }
  132. }
  133. // Registration form submission handler
  134. class RegisterFormHandler : Object, RouteHandler {
  135. public async HttpResult handle_route(HttpContext context, RouteContext route_context) throws Error {
  136. if (!context.request.is_post()) {
  137. return new HttpStringResult("Please use POST method");
  138. }
  139. FormData form_data = yield FormDataParser.parse(
  140. context.request.request_body,
  141. context.request.content_type
  142. );
  143. var username = form_data.get_field("username");
  144. var password = form_data.get_field("password");
  145. var age_str = form_data.get_field_or_default("age", "0");
  146. var country = form_data.get_field_or_default("country", "us");
  147. var bio = form_data.get_field_or_default("bio", "");
  148. var newsletter = form_data.get_field("newsletter");
  149. // Validation
  150. if (username == null || username == "") {
  151. return new HttpStringResult(@"{ \"error\": \"Username is required\" }")
  152. .set_header("Content-Type", "application/json");
  153. }
  154. if (password == null || password == "") {
  155. return new HttpStringResult(@"{ \"error\": \"Password is required\" }")
  156. .set_header("Content-Type", "application/json");
  157. }
  158. var age = int.parse(age_str);
  159. if (age < 18) {
  160. return new HttpStringResult(@"{ \"error\": \"You must be at least 18 years old\" }")
  161. .set_header("Content-Type", "application/json");
  162. }
  163. // Build JSON response using Series
  164. var json_parts = new Series<string>();
  165. json_parts.add(@"{ \"success\": true, \"user\": {");
  166. json_parts.add(@" \"username\": \"$username\",");
  167. json_parts.add(@" \"age\": $age,");
  168. json_parts.add(@" \"country\": \"$country\",");
  169. json_parts.add(@" \"bio\": \"$(bio.replace("\"", "\\\""))\",");
  170. json_parts.add(@" \"newsletter\": $(newsletter != null ? "true" : "false")");
  171. json_parts.add(@"} }");
  172. var json_string = json_parts.to_immutable_buffer()
  173. .aggregate<string>("", (acc, s) => acc + s);
  174. return new HttpStringResult(json_string)
  175. .set_header("Content-Type", "application/json");
  176. }
  177. }
  178. // Search form submission handler
  179. class SearchFormHandler : Object, RouteHandler {
  180. public async HttpResult handle_route(HttpContext context, RouteContext route_context) throws Error {
  181. if (!context.request.is_post()) {
  182. return new HttpStringResult("Please use POST method");
  183. }
  184. FormData form_data = yield FormDataParser.parse(
  185. context.request.request_body,
  186. context.request.content_type
  187. );
  188. var query = form_data.get_field("query");
  189. var category = form_data.get_field_or_default("category", "");
  190. var min_price = double.parse(form_data.get_field_or_default("min_price", "0"));
  191. var max_price = double.parse(form_data.get_field_or_default("max_price", "999999"));
  192. if (query == null || query == "") {
  193. return new HttpStringResult(@"{ \"error\": \"Search query is required\" }")
  194. .set_header("Content-Type", "application/json");
  195. }
  196. // Simulated search results using Enumerable operations
  197. var all_products = new Series<Product>();
  198. all_products.add(new Product(1, "Book A", "books", 15.99));
  199. all_products.add(new Product(2, "Book B", "books", 24.99));
  200. all_products.add(new Product(3, "Laptop", "electronics", 999.99));
  201. all_products.add(new Product(4, "Phone", "electronics", 699.99));
  202. all_products.add(new Product(5, "Shirt", "clothing", 29.99));
  203. all_products.add(new Product(6, "Pants", "clothing", 49.99));
  204. // Filter results using Enumerable operations
  205. var results = all_products.to_immutable_buffer()
  206. .where(p => {
  207. var matches_query = p.name.down().contains(query.down());
  208. var matches_category = category == "" || p.category == category;
  209. var matches_price = p.price >= min_price && p.price <= max_price;
  210. return matches_query && matches_category && matches_price;
  211. });
  212. var json_parts = new Series<string>();
  213. json_parts.add(@"{ \"query\": \"$query\", \"category\": \"$category\", \"min_price\": $min_price, \"max_price\": $max_price, \"results\": [");
  214. bool first = true;
  215. results.iterate((product) => {
  216. if (!first) json_parts.add(", ");
  217. json_parts.add(product.to_json());
  218. first = false;
  219. });
  220. json_parts.add("] }");
  221. var json_string = json_parts.to_immutable_buffer()
  222. .aggregate<string>("", (acc, s) => acc + s);
  223. return new HttpStringResult(json_string)
  224. .set_header("Content-Type", "application/json");
  225. }
  226. }
  227. // File upload handler (multipart/form-data)
  228. class FileUploadHandler : Object, RouteHandler {
  229. public async HttpResult handle_route(HttpContext context, RouteContext route_context) throws Error {
  230. if (!context.request.is_post()) {
  231. return new HttpStringResult("Please use POST method");
  232. }
  233. FormData form_data = yield FormDataParser.parse(
  234. context.request.request_body,
  235. context.request.content_type
  236. );
  237. var description = form_data.get_field_or_default("description", "");
  238. var file = form_data.get_file("file");
  239. var parts = new Series<string>();
  240. parts.add("File Upload Result\n");
  241. parts.add("==================\n\n");
  242. parts.add(@"Description: $description\n");
  243. if (file != null) {
  244. parts.add(@"\nFile Information:\n");
  245. parts.add(@" Field Name: $(file.field_name)\n");
  246. parts.add(@" Filename: $(file.filename)\n");
  247. parts.add(@" Content-Type: $(file.content_type)\n");
  248. parts.add(@" Size: $(file.data.length) bytes\n");
  249. } else {
  250. parts.add("\nNo file uploaded.\n");
  251. }
  252. var result = parts.to_immutable_buffer()
  253. .aggregate<string>("", (acc, s) => acc + s);
  254. return new HttpStringResult(result);
  255. }
  256. }
  257. // Form debug tool handler
  258. class FormDebugHandler : Object, RouteHandler {
  259. public async HttpResult handle_route(HttpContext context, RouteContext route_context) throws Error {
  260. FormData? form_data = null;
  261. string? body_text = null;
  262. // Try to parse form data if this is a POST with form content
  263. if (context.request.is_post() &&
  264. (context.request.is_form_urlencoded() || context.request.is_multipart())) {
  265. try {
  266. form_data = yield FormDataParser.parse(
  267. context.request.request_body,
  268. context.request.content_type
  269. );
  270. } catch (Error e) {
  271. body_text = @"Error parsing form data: $(e.message)";
  272. }
  273. }
  274. // Get counts (uint type)
  275. uint field_count = form_data != null ? form_data.field_count() : 0;
  276. uint file_count = form_data != null ? form_data.file_count() : 0;
  277. var parts = new Series<string>();
  278. parts.add("""<!DOCTYPE html>
  279. <html>
  280. <head>
  281. <title>Form Debug Tool</title>
  282. <style>
  283. body { font-family: monospace; max-width: 800px; margin: 40px auto; padding: 20px; background: #f5f5f5; }
  284. .section { background: white; padding: 20px; margin: 20px 0; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
  285. h1 { color: #333; }
  286. h2 { color: #666; border-bottom: 2px solid #007bff; padding-bottom: 10px; }
  287. table { width: 100%; border-collapse: collapse; margin: 10px 0; }
  288. th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
  289. th { background: #007bff; color: white; }
  290. tr:hover { background: #f9f9f9; }
  291. .empty { color: #999; font-style: italic; }
  292. a { color: #007bff; text-decoration: none; }
  293. a:hover { text-decoration: underline; }
  294. form { margin: 20px 0; }
  295. input, textarea { width: 100%; padding: 8px; margin: 5px 0; box-sizing: border-box; }
  296. button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; }
  297. </style>
  298. </head>
  299. <body>
  300. <h1>Form Debug Tool</h1>
  301. <div class="section">
  302. <h2>Test Form</h2>
  303. <form action="/form-debug" method="POST" enctype="multipart/form-data">
  304. <label>Text Field: <input type="text" name="test_field" value="test value"></label>
  305. <label>File: <input type="file" name="test_file"></label>
  306. <button type="submit">Submit Test</button>
  307. </form>
  308. </div>
  309. <div class="section">
  310. <h2>Request Information</h2>
  311. <table>
  312. <tr><th>Method</th><td>$(context.request.method)</td></tr>
  313. <tr><th>Path</th><td>$(context.request.raw_path)</td></tr>
  314. <tr><th>Content Type</th><td>$(context.request.content_type)</td></tr>
  315. <tr><th>Content Length</th><td>$(context.request.content_length)</td></tr>
  316. <tr><th>Is Form URL Encoded</th><td>$(context.request.is_form_urlencoded())</td></tr>
  317. <tr><th>Is Multipart</th><td>$(context.request.is_multipart())</td></tr>
  318. </table>
  319. </div>
  320. """);
  321. if (form_data != null) {
  322. parts.add(@" <div class=\"section\">\n");
  323. parts.add(@" <h2>Form Fields ($field_count fields)</h2>\n");
  324. if (field_count == 0) {
  325. parts.add(@" <p class=\"empty\">No form fields received.</p>\n");
  326. } else {
  327. parts.add(@" <table>\n");
  328. parts.add(@" <tr><th>Field Name</th><th>Value</th></tr>\n");
  329. form_data.fields.to_immutable_buffer()
  330. .iterate((grouping) => {
  331. grouping.iterate((value) => {
  332. parts.add(@" <tr><td>$(grouping.key)</td><td>$(value.escape(""))</td></tr>\n");
  333. });
  334. });
  335. parts.add(@" </table>\n");
  336. }
  337. parts.add(@" </div>\n");
  338. parts.add(@" <div class=\"section\">\n");
  339. parts.add(@" <h2>File Uploads ($file_count files)</h2>\n");
  340. if (file_count == 0) {
  341. parts.add(@" <p class=\"empty\">No files uploaded.</p>\n");
  342. } else {
  343. parts.add(@" <table>\n");
  344. parts.add(@" <tr><th>Field Name</th><th>Filename</th><th>Content-Type</th><th>Size</th></tr>\n");
  345. form_data.files.to_immutable_buffer()
  346. .iterate((grouping) => {
  347. grouping.iterate((file) => {
  348. parts.add(@" <tr><td>$(file.field_name)</td><td>$(file.filename)</td><td>$(file.content_type)</td><td>$(file.data.length) bytes</td></tr>\n");
  349. });
  350. });
  351. parts.add(@" </table>\n");
  352. }
  353. parts.add(@" </div>\n");
  354. } else if (body_text != null) {
  355. parts.add(@" <div class=\"section\">\n");
  356. parts.add(@" <h2>Error</h2>\n");
  357. parts.add(@" <pre>$(body_text.escape(""))</pre>\n");
  358. parts.add(@" </div>\n");
  359. }
  360. parts.add(""" <div class="section">
  361. <h2>Query Parameters</h2>
  362. """);
  363. var query_count = context.request.query_params.to_immutable_buffer().count();
  364. if (query_count == 0) {
  365. parts.add(@" <p class=\"empty\">No query parameters.</p>\n");
  366. } else {
  367. parts.add(@" <table>\n");
  368. parts.add(@" <tr><th>Parameter</th><th>Value</th></tr>\n");
  369. context.request.query_params.to_immutable_buffer()
  370. .iterate((grouping) => {
  371. grouping.iterate((value) => {
  372. parts.add(@" <tr><td>$(grouping.key)</td><td>$(value.escape(""))</td></tr>\n");
  373. });
  374. });
  375. parts.add(@" </table>\n");
  376. }
  377. parts.add(""" </div>
  378. <p><a href="/">Back to Forms</a></p>
  379. </body>
  380. </html>""");
  381. var result = parts.to_immutable_buffer()
  382. .aggregate<string>("", (acc, s) => acc + s);
  383. return new HttpStringResult(result)
  384. .set_header("Content-Type", "text/html");
  385. }
  386. }
  387. // Helper class for product data
  388. class Product {
  389. public int id { get; private set; }
  390. public string name { get; private set; }
  391. public string category { get; private set; }
  392. public double price { get; private set; }
  393. public Product(int id, string name, string category, double price) {
  394. this.id = id;
  395. this.name = name;
  396. this.category = category;
  397. this.price = price;
  398. }
  399. public string to_json() {
  400. return @"{ \"id\": $id, \"name\": \"$name\", \"category\": \"$category\", \"price\": $price }";
  401. }
  402. }
  403. void main() {
  404. var router = new Router();
  405. var server = new Server(8084, router);
  406. // Register handlers
  407. router.get("/", new FormPageHandler());
  408. router.post("/submit-simple", new SimpleFormHandler());
  409. router.post("/submit-register", new RegisterFormHandler());
  410. router.post("/submit-search", new SearchFormHandler());
  411. router.post("/submit-file", new FileUploadHandler());
  412. router.map("/form-debug", new FormDebugHandler()); // Handles both GET and POST
  413. print("Form Data Example Server running on port 8084\n");
  414. print("Open http://localhost:8084/ in your browser to try the forms\n");
  415. server.run();
  416. }