FormData.vala 20 KB

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