FormData.vala 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 Endpoint.
  8. * Shows both application/x-www-form-urlencoded and multipart/form-data handling.
  9. */
  10. // HTML form page handler
  11. class FormPageEndpoint : Object, Endpoint {
  12. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  13. var res = 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. return res;
  102. }
  103. }
  104. // Simple form submission handler
  105. class SimpleFormEndpoint : Object, Endpoint {
  106. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  107. // Parse form data asynchronously from the request body
  108. FormData form_data = yield FormDataParser.parse(
  109. context.request.request_body,
  110. context.request.content_type
  111. );
  112. var name = form_data.get_field_or_default("name", "Anonymous");
  113. var email = form_data.get_field_or_default("email", "no-email@example.com");
  114. var parts = new Series<string>();
  115. parts.add("Form Submission Received!\n");
  116. parts.add("=========================\n\n");
  117. parts.add(@"Name: $name\n");
  118. parts.add(@"Email: $email\n");
  119. parts.add("\nAll form data:\n");
  120. form_data.fields.to_immutable_buffer()
  121. .iterate((grouping) => {
  122. grouping.iterate((value) => {
  123. parts.add(@" $(grouping.key): $value\n");
  124. });
  125. });
  126. var result = parts.to_immutable_buffer()
  127. .aggregate<string>("", (acc, s) => acc + s);
  128. return new HttpStringResult(result);
  129. }
  130. }
  131. // Registration form submission handler
  132. class RegisterFormEndpoint : Object, Endpoint {
  133. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  134. FormData form_data = yield FormDataParser.parse(
  135. context.request.request_body,
  136. context.request.content_type
  137. );
  138. var username = form_data.get_field("username");
  139. var password = form_data.get_field("password");
  140. var age_str = form_data.get_field_or_default("age", "0");
  141. var country = form_data.get_field_or_default("country", "us");
  142. var bio = form_data.get_field_or_default("bio", "");
  143. var newsletter = form_data.get_field("newsletter");
  144. // Validation
  145. if (username == null || username == "") {
  146. return new HttpStringResult(@"{ \"error\": \"Username is required\" }")
  147. .set_header("Content-Type", "application/json");
  148. }
  149. if (password == null || password == "") {
  150. return new HttpStringResult(@"{ \"error\": \"Password is required\" }")
  151. .set_header("Content-Type", "application/json");
  152. }
  153. var age = int.parse(age_str);
  154. if (age < 18) {
  155. return new HttpStringResult(@"{ \"error\": \"You must be at least 18 years old\" }")
  156. .set_header("Content-Type", "application/json");
  157. }
  158. // Build JSON response using Series
  159. var json_parts = new Series<string>();
  160. json_parts.add(@"{ \"success\": true, \"user\": {");
  161. json_parts.add(@" \"username\": \"$username\",");
  162. json_parts.add(@" \"age\": $age,");
  163. json_parts.add(@" \"country\": \"$country\",");
  164. json_parts.add(@" \"bio\": \"$(bio.replace("\"", "\\\""))\",");
  165. json_parts.add(@" \"newsletter\": $(newsletter != null ? "true" : "false")");
  166. json_parts.add(@"} }");
  167. var json_string = json_parts.to_immutable_buffer()
  168. .aggregate<string>("", (acc, s) => acc + s);
  169. return new HttpStringResult(json_string)
  170. .set_header("Content-Type", "application/json");
  171. }
  172. }
  173. // Search form submission handler
  174. class SearchFormEndpoint : Object, Endpoint {
  175. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  176. FormData form_data = yield FormDataParser.parse(
  177. context.request.request_body,
  178. context.request.content_type
  179. );
  180. var query = form_data.get_field("query");
  181. var category = form_data.get_field_or_default("category", "");
  182. var min_price = double.parse(form_data.get_field_or_default("min_price", "0"));
  183. var max_price = double.parse(form_data.get_field_or_default("max_price", "999999"));
  184. if (query == null || query == "") {
  185. return new HttpStringResult(@"{ \"error\": \"Search query is required\" }")
  186. .set_header("Content-Type", "application/json");
  187. }
  188. // Simulated search results using Enumerable operations
  189. var all_products = new Series<Product>();
  190. all_products.add(new Product(1, "Book A", "books", 15.99));
  191. all_products.add(new Product(2, "Book B", "books", 24.99));
  192. all_products.add(new Product(3, "Laptop", "electronics", 999.99));
  193. all_products.add(new Product(4, "Phone", "electronics", 699.99));
  194. all_products.add(new Product(5, "Shirt", "clothing", 29.99));
  195. all_products.add(new Product(6, "Pants", "clothing", 49.99));
  196. // Filter results using Enumerable operations
  197. var results = all_products.to_immutable_buffer()
  198. .where(p => {
  199. var matches_query = p.name.down().contains(query.down());
  200. var matches_category = category == "" || p.category == category;
  201. var matches_price = p.price >= min_price && p.price <= max_price;
  202. return matches_query && matches_category && matches_price;
  203. });
  204. var json_parts = new Series<string>();
  205. json_parts.add(@"{ \"query\": \"$query\", \"category\": \"$category\", \"min_price\": $min_price, \"max_price\": $max_price, \"results\": [");
  206. bool first = true;
  207. results.iterate((product) => {
  208. if (!first) json_parts.add(", ");
  209. json_parts.add(product.to_json());
  210. first = false;
  211. });
  212. json_parts.add("] }");
  213. var json_string = json_parts.to_immutable_buffer()
  214. .aggregate<string>("", (acc, s) => acc + s);
  215. return new HttpStringResult(json_string)
  216. .set_header("Content-Type", "application/json");
  217. }
  218. }
  219. // File upload handler (multipart/form-data)
  220. class FileUploadEndpoint : Object, Endpoint {
  221. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  222. FormData form_data = yield FormDataParser.parse(
  223. context.request.request_body,
  224. context.request.content_type
  225. );
  226. var description = form_data.get_field_or_default("description", "");
  227. var file = form_data.get_file("file");
  228. var parts = new Series<string>();
  229. parts.add("File Upload Result\n");
  230. parts.add("==================\n\n");
  231. parts.add(@"Description: $description\n");
  232. if (file != null) {
  233. parts.add(@"\nFile Information:\n");
  234. parts.add(@" Field Name: $(file.field_name)\n");
  235. parts.add(@" Filename: $(file.filename)\n");
  236. parts.add(@" Content-Type: $(file.content_type)\n");
  237. parts.add(@" Size: $(file.data.length) bytes\n");
  238. } else {
  239. parts.add("\nNo file uploaded.\n");
  240. }
  241. var result = parts.to_immutable_buffer()
  242. .aggregate<string>("", (acc, s) => acc + s);
  243. return new HttpStringResult(result);
  244. }
  245. }
  246. // Form debug tool handler
  247. class FormDebugEndpoint : Object, Endpoint {
  248. public async HttpResult handle_request(HttpContext context, RouteContext route) throws Error {
  249. FormData? form_data = null;
  250. string? body_text = null;
  251. // Try to parse form data if this is a POST with form content
  252. if (context.request.method == Method.POST &&
  253. (context.request.is_form_urlencoded() || context.request.is_multipart())) {
  254. try {
  255. form_data = yield FormDataParser.parse(
  256. context.request.request_body,
  257. context.request.content_type
  258. );
  259. } catch (Error e) {
  260. body_text = @"Error parsing form data: $(e.message)";
  261. }
  262. }
  263. // Get counts (uint type)
  264. uint field_count = form_data != null ? form_data.field_count() : 0;
  265. uint file_count = form_data != null ? form_data.file_count() : 0;
  266. var parts = new Series<string>();
  267. parts.add("""<!DOCTYPE html>
  268. <html>
  269. <head>
  270. <title>Form Debug Tool</title>
  271. <style>
  272. body { font-family: monospace; max-width: 800px; margin: 40px auto; padding: 20px; background: #f5f5f5; }
  273. .section { background: white; padding: 20px; margin: 20px 0; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
  274. h1 { color: #333; }
  275. h2 { color: #666; border-bottom: 2px solid #007bff; padding-bottom: 10px; }
  276. table { width: 100%; border-collapse: collapse; margin: 10px 0; }
  277. th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
  278. th { background: #007bff; color: white; }
  279. tr:hover { background: #f9f9f9; }
  280. .empty { color: #999; font-style: italic; }
  281. a { color: #007bff; text-decoration: none; }
  282. a:hover { text-decoration: underline; }
  283. form { margin: 20px 0; }
  284. input, textarea { width: 100%; padding: 8px; margin: 5px 0; box-sizing: border-box; }
  285. button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; }
  286. </style>
  287. </head>
  288. <body>
  289. <h1>Form Debug Tool</h1>
  290. <div class="section">
  291. <h2>Test Form</h2>
  292. <form action="/form-debug" method="POST" enctype="multipart/form-data">
  293. <label>Text Field: <input type="text" name="test_field" value="test value"></label>
  294. <label>File: <input type="file" name="test_file"></label>
  295. <button type="submit">Submit Test</button>
  296. </form>
  297. </div>
  298. <div class="section">
  299. <h2>Request Information</h2>
  300. <table>
  301. <tr><th>Method</th><td>$(context.request.method)</td></tr>
  302. <tr><th>Path</th><td>$(context.request.raw_path)</td></tr>
  303. <tr><th>Content Type</th><td>$(context.request.content_type)</td></tr>
  304. <tr><th>Content Length</th><td>$(context.request.content_length)</td></tr>
  305. <tr><th>Is Form URL Encoded</th><td>$(context.request.is_form_urlencoded())</td></tr>
  306. <tr><th>Is Multipart</th><td>$(context.request.is_multipart())</td></tr>
  307. </table>
  308. </div>
  309. """);
  310. if (form_data != null) {
  311. parts.add(@" <div class=\"section\">\n");
  312. parts.add(@" <h2>Form Fields ($field_count fields)</h2>\n");
  313. if (field_count == 0) {
  314. parts.add(@" <p class=\"empty\">No form fields received.</p>\n");
  315. } else {
  316. parts.add(@" <table>\n");
  317. parts.add(@" <tr><th>Field Name</th><th>Value</th></tr>\n");
  318. form_data.fields.to_immutable_buffer()
  319. .iterate((grouping) => {
  320. grouping.iterate((value) => {
  321. parts.add(@" <tr><td>$(grouping.key)</td><td>$(value.escape(""))</td></tr>\n");
  322. });
  323. });
  324. parts.add(@" </table>\n");
  325. }
  326. parts.add(@" </div>\n");
  327. parts.add(@" <div class=\"section\">\n");
  328. parts.add(@" <h2>File Uploads ($file_count files)</h2>\n");
  329. if (file_count == 0) {
  330. parts.add(@" <p class=\"empty\">No files uploaded.</p>\n");
  331. } else {
  332. parts.add(@" <table>\n");
  333. parts.add(@" <tr><th>Field Name</th><th>Filename</th><th>Content-Type</th><th>Size</th></tr>\n");
  334. form_data.files.to_immutable_buffer()
  335. .iterate((grouping) => {
  336. grouping.iterate((file) => {
  337. 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");
  338. });
  339. });
  340. parts.add(@" </table>\n");
  341. }
  342. parts.add(@" </div>\n");
  343. } else if (body_text != null) {
  344. parts.add(@" <div class=\"section\">\n");
  345. parts.add(@" <h2>Error</h2>\n");
  346. parts.add(@" <pre>$(body_text.escape(""))</pre>\n");
  347. parts.add(@" </div>\n");
  348. }
  349. parts.add(""" <div class="section">
  350. <h2>Query Parameters</h2>
  351. """);
  352. var query_count = context.request.query_params.to_immutable_buffer().count();
  353. if (query_count == 0) {
  354. parts.add(@" <p class=\"empty\">No query parameters.</p>\n");
  355. } else {
  356. parts.add(@" <table>\n");
  357. parts.add(@" <tr><th>Parameter</th><th>Value</th></tr>\n");
  358. context.request.query_params.to_immutable_buffer()
  359. .iterate((grouping) => {
  360. grouping.iterate((value) => {
  361. parts.add(@" <tr><td>$(grouping.key)</td><td>$(value.escape(""))</td></tr>\n");
  362. });
  363. });
  364. parts.add(@" </table>\n");
  365. }
  366. parts.add(""" </div>
  367. <p><a href="/">Back to Forms</a></p>
  368. </body>
  369. </html>""");
  370. var result = parts.to_immutable_buffer()
  371. .aggregate<string>("", (acc, s) => acc + s);
  372. return new HttpStringResult(result)
  373. .set_header("Content-Type", "text/html");
  374. }
  375. }
  376. // Helper class for product data
  377. class Product {
  378. public int id { get; private set; }
  379. public string name { get; private set; }
  380. public string category { get; private set; }
  381. public double price { get; private set; }
  382. public Product(int id, string name, string category, double price) {
  383. this.id = id;
  384. this.name = name;
  385. this.category = category;
  386. this.price = price;
  387. }
  388. public string to_json() {
  389. return @"{ \"id\": $id, \"name\": \"$name\", \"category\": \"$category\", \"price\": $price }";
  390. }
  391. }
  392. void main() {
  393. var application = new WebApplication(8084);
  394. // Register compression components
  395. application.container.register_singleton<GzipCompressor>(() => new GzipCompressor());
  396. application.container.register_singleton<ZstdCompressor>(() => new ZstdCompressor());
  397. application.container.register_singleton<BrotliCompressor>(() => new BrotliCompressor());
  398. // Register endpoints
  399. application.container.register_scoped<Endpoint>(() => new FormPageEndpoint())
  400. .with_metadata<EndpointRoute>(new EndpointRoute("/"));
  401. application.container.register_scoped<Endpoint>(() => new SimpleFormEndpoint())
  402. .with_metadata<EndpointRoute>(new EndpointRoute("/submit-simple"));
  403. application.container.register_scoped<Endpoint>(() => new RegisterFormEndpoint())
  404. .with_metadata<EndpointRoute>(new EndpointRoute("/submit-register"));
  405. application.container.register_scoped<Endpoint>(() => new SearchFormEndpoint())
  406. .with_metadata<EndpointRoute>(new EndpointRoute("/submit-search"));
  407. application.container.register_scoped<Endpoint>(() => new FileUploadEndpoint())
  408. .with_metadata<EndpointRoute>(new EndpointRoute("/submit-file"));
  409. application.container.register_scoped<Endpoint>(() => new FormDebugEndpoint())
  410. .with_metadata<EndpointRoute>(new EndpointRoute("/form-debug"));
  411. print("Form Data Example Server running on port 8084\n");
  412. print("Open http://localhost:8084/ in your browser to try the forms\n");
  413. application.run();
  414. }