FormData.vala 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 string route { get { return "/"; } }
  13. public Method[] methods { owned get { return { Method.GET }; } }
  14. public async HttpResult handle_request(HttpContext context, RouteInformation route) throws Error {
  15. return new HttpStringResult("""<!DOCTYPE html>
  16. <html>
  17. <head>
  18. <title>Form Data Example</title>
  19. <style>
  20. body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; padding: 20px; }
  21. h1 { color: #333; }
  22. .form-section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
  23. label { display: block; margin: 10px 0 5px; font-weight: bold; }
  24. input, textarea, select { width: 100%; padding: 8px; margin: 5px 0; box-sizing: border-box; }
  25. button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; }
  26. button:hover { background: #0056b3; }
  27. a { color: #007bff; text-decoration: none; }
  28. a:hover { text-decoration: underline; }
  29. </style>
  30. </head>
  31. <body>
  32. <h1>Form Data Examples</h1>
  33. <div class="form-section">
  34. <h2>Simple Form (URL Encoded)</h2>
  35. <form action="/submit-simple" method="POST">
  36. <label for="name">Name:</label>
  37. <input type="text" id="name" name="name" required>
  38. <label for="email">Email:</label>
  39. <input type="email" id="email" name="email" required>
  40. <button type="submit">Submit</button>
  41. </form>
  42. </div>
  43. <div class="form-section">
  44. <h2>Registration Form (URL Encoded)</h2>
  45. <form action="/submit-register" method="POST">
  46. <label for="username">Username:</label>
  47. <input type="text" id="username" name="username" required>
  48. <label for="password">Password:</label>
  49. <input type="password" id="password" name="password" required>
  50. <label for="age">Age:</label>
  51. <input type="number" id="age" name="age" min="18" max="120">
  52. <label for="country">Country:</label>
  53. <select id="country" name="country">
  54. <option value="us">United States</option>
  55. <option value="uk">United Kingdom</option>
  56. <option value="nz">New Zealand</option>
  57. <option value="au">Australia</option>
  58. </select>
  59. <label for="bio">Bio:</label>
  60. <textarea id="bio" name="bio" rows="4"></textarea>
  61. <label>
  62. <input type="checkbox" name="newsletter" value="yes"> Subscribe to newsletter
  63. </label>
  64. <button type="submit">Register</button>
  65. </form>
  66. </div>
  67. <div class="form-section">
  68. <h2>Search Form (URL Encoded)</h2>
  69. <form action="/submit-search" method="POST">
  70. <label for="query">Search Query:</label>
  71. <input type="text" id="query" name="query" required>
  72. <label for="category">Category:</label>
  73. <select id="category" name="category">
  74. <option value="">All Categories</option>
  75. <option value="books">Books</option>
  76. <option value="electronics">Electronics</option>
  77. <option value="clothing">Clothing</option>
  78. </select>
  79. <label for="min_price">Min Price:</label>
  80. <input type="number" id="min_price" name="min_price" min="0" step="0.01">
  81. <label for="max_price">Max Price:</label>
  82. <input type="number" id="max_price" name="max_price" min="0" step="0.01">
  83. <button type="submit">Search</button>
  84. </form>
  85. </div>
  86. <div class="form-section">
  87. <h2>File Upload (Multipart)</h2>
  88. <form action="/submit-file" method="POST" enctype="multipart/form-data">
  89. <label for="description">Description:</label>
  90. <input type="text" id="description" name="description">
  91. <label for="file">File:</label>
  92. <input type="file" id="file" name="file">
  93. <button type="submit">Upload</button>
  94. </form>
  95. </div>
  96. <div class="form-section">
  97. <h2>Links</h2>
  98. <p><a href="/form-debug">Form Debug Tool</a></p>
  99. </div>
  100. </body>
  101. </html>""")
  102. .set_header("Content-Type", "text/html");
  103. }
  104. }
  105. // Simple form submission handler
  106. class SimpleFormEndpoint : Object, Endpoint {
  107. public string route { get { return "/submit-simple"; } }
  108. public Method[] methods { owned get { return { Method.POST }; } }
  109. public async HttpResult handle_request(HttpContext context, RouteInformation route) throws Error {
  110. // Parse form data asynchronously from the request body
  111. FormData form_data = yield FormDataParser.parse(
  112. context.request.request_body,
  113. context.request.content_type
  114. );
  115. var name = form_data.get_field_or_default("name", "Anonymous");
  116. var email = form_data.get_field_or_default("email", "no-email@example.com");
  117. var parts = new Series<string>();
  118. parts.add("Form Submission Received!\n");
  119. parts.add("=========================\n\n");
  120. parts.add(@"Name: $name\n");
  121. parts.add(@"Email: $email\n");
  122. parts.add("\nAll form data:\n");
  123. form_data.fields.to_immutable_buffer()
  124. .iterate((grouping) => {
  125. grouping.iterate((value) => {
  126. parts.add(@" $(grouping.key): $value\n");
  127. });
  128. });
  129. var result = parts.to_immutable_buffer()
  130. .aggregate<string>("", (acc, s) => acc + s);
  131. return new HttpStringResult(result);
  132. }
  133. }
  134. // Registration form submission handler
  135. class RegisterFormEndpoint : Object, Endpoint {
  136. public string route { get { return "/submit-register"; } }
  137. public Method[] methods { owned get { return { Method.POST }; } }
  138. public async HttpResult handle_request(HttpContext context, RouteInformation route) throws Error {
  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 SearchFormEndpoint : Object, Endpoint {
  180. public string route { get { return "/submit-search"; } }
  181. public Method[] methods { owned get { return { Method.POST }; } }
  182. public async HttpResult handle_request(HttpContext context, RouteInformation route) throws Error {
  183. FormData form_data = yield FormDataParser.parse(
  184. context.request.request_body,
  185. context.request.content_type
  186. );
  187. var query = form_data.get_field("query");
  188. var category = form_data.get_field_or_default("category", "");
  189. var min_price = double.parse(form_data.get_field_or_default("min_price", "0"));
  190. var max_price = double.parse(form_data.get_field_or_default("max_price", "999999"));
  191. if (query == null || query == "") {
  192. return new HttpStringResult(@"{ \"error\": \"Search query is required\" }")
  193. .set_header("Content-Type", "application/json");
  194. }
  195. // Simulated search results using Enumerable operations
  196. var all_products = new Series<Product>();
  197. all_products.add(new Product(1, "Book A", "books", 15.99));
  198. all_products.add(new Product(2, "Book B", "books", 24.99));
  199. all_products.add(new Product(3, "Laptop", "electronics", 999.99));
  200. all_products.add(new Product(4, "Phone", "electronics", 699.99));
  201. all_products.add(new Product(5, "Shirt", "clothing", 29.99));
  202. all_products.add(new Product(6, "Pants", "clothing", 49.99));
  203. // Filter results using Enumerable operations
  204. var results = all_products.to_immutable_buffer()
  205. .where(p => {
  206. var matches_query = p.name.down().contains(query.down());
  207. var matches_category = category == "" || p.category == category;
  208. var matches_price = p.price >= min_price && p.price <= max_price;
  209. return matches_query && matches_category && matches_price;
  210. });
  211. var json_parts = new Series<string>();
  212. json_parts.add(@"{ \"query\": \"$query\", \"category\": \"$category\", \"min_price\": $min_price, \"max_price\": $max_price, \"results\": [");
  213. bool first = true;
  214. results.iterate((product) => {
  215. if (!first) json_parts.add(", ");
  216. json_parts.add(product.to_json());
  217. first = false;
  218. });
  219. json_parts.add("] }");
  220. var json_string = json_parts.to_immutable_buffer()
  221. .aggregate<string>("", (acc, s) => acc + s);
  222. return new HttpStringResult(json_string)
  223. .set_header("Content-Type", "application/json");
  224. }
  225. }
  226. // File upload handler (multipart/form-data)
  227. class FileUploadEndpoint : Object, Endpoint {
  228. public string route { get { return "/submit-file"; } }
  229. public Method[] methods { owned get { return { Method.POST }; } }
  230. public async HttpResult handle_request(HttpContext context, RouteInformation route) throws Error {
  231. FormData form_data = yield FormDataParser.parse(
  232. context.request.request_body,
  233. context.request.content_type
  234. );
  235. var description = form_data.get_field_or_default("description", "");
  236. var file = form_data.get_file("file");
  237. var parts = new Series<string>();
  238. parts.add("File Upload Result\n");
  239. parts.add("==================\n\n");
  240. parts.add(@"Description: $description\n");
  241. if (file != null) {
  242. parts.add(@"\nFile Information:\n");
  243. parts.add(@" Field Name: $(file.field_name)\n");
  244. parts.add(@" Filename: $(file.filename)\n");
  245. parts.add(@" Content-Type: $(file.content_type)\n");
  246. parts.add(@" Size: $(file.data.length) bytes\n");
  247. } else {
  248. parts.add("\nNo file uploaded.\n");
  249. }
  250. var result = parts.to_immutable_buffer()
  251. .aggregate<string>("", (acc, s) => acc + s);
  252. return new HttpStringResult(result);
  253. }
  254. }
  255. // Form debug tool handler
  256. class FormDebugEndpoint : Object, Endpoint {
  257. public string route { get { return "/form-debug"; } }
  258. public Method[] methods { owned get { return { Method.GET, Method.POST }; } }
  259. public async HttpResult handle_request(HttpContext context, RouteInformation route) 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.method == Method.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 EndpointRouter()
  405. .add_endpoint(new FormPageEndpoint())
  406. .add_endpoint(new SimpleFormEndpoint())
  407. .add_endpoint(new RegisterFormEndpoint())
  408. .add_endpoint(new SearchFormEndpoint())
  409. .add_endpoint(new FileUploadEndpoint())
  410. .add_endpoint(new FormDebugEndpoint());
  411. var pipeline = new Pipeline()
  412. .add_component(new Compression())
  413. .add_component(router);
  414. var server = new Server(8084, pipeline);
  415. print("Form Data Example Server running on port 8084\n");
  416. print("Open http://localhost:8084/ in your browser to try the forms\n");
  417. server.run();
  418. }