PathRouting.vala 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. using Astralis;
  2. using Invercargill;
  3. using Invercargill.DataStructures;
  4. /**
  5. * PathRouting Example
  6. *
  7. * Demonstrates path component parsing and routing in Astralis.
  8. * Uses Invercargill Enumerable for path processing.
  9. */
  10. void main() {
  11. var router = new Router();
  12. var server = new Server(8082, router);
  13. // Root path
  14. router.map_func("/", (context) => {
  15. return new BufferedHttpResult.from_string(
  16. """Welcome to the Path Routing Example!
  17. Available endpoints:
  18. GET / - This message
  19. GET /hello - Simple greeting
  20. GET /hello/{name} - Greeting with name
  21. GET /users - List all users
  22. GET /users/{id} - Get user by ID
  23. GET /users/{id}/posts - Get posts for a user
  24. GET /api/v1/status - API status
  25. GET /api/v1/items/{id} - Get item by ID
  26. GET /files/{category}/{name} - Get file by category and name
  27. """
  28. );
  29. });
  30. // Simple path
  31. router.map_func("/hello", (context) => {
  32. return new BufferedHttpResult.from_string("Hello, World!");
  33. });
  34. // Path with one component (simulated dynamic routing)
  35. router.map_func("/hello/", (context) => {
  36. var components = context.request.path_components.to_vector();
  37. if (components.count() < 2) {
  38. return new BufferedHttpResult.from_string(
  39. "Please provide a name: /hello/{name}",
  40. StatusCode.BAD_REQUEST
  41. );
  42. }
  43. var name = components[1];
  44. return new BufferedHttpResult.from_string(@"Hello, $name!");
  45. });
  46. // Users list endpoint
  47. router.map_func("/users", (context) => {
  48. // Simulated user data using Invercargill data structures
  49. var users = new Series<User>();
  50. users.add(new User(1, "Alice", "alice@example.com"));
  51. users.add(new User(2, "Bob", "bob@example.com"));
  52. users.add(new User(3, "Charlie", "charlie@example.com"));
  53. var json_parts = new Series<string>();
  54. json_parts.add(@"{ \"users\": [");
  55. bool first = true;
  56. users.to_immutable_buffer().iterate((user) => {
  57. if (!first) json_parts.add(", ");
  58. json_parts.add(user.to_json());
  59. first = false;
  60. });
  61. json_parts.add("] }");
  62. var json_string = json_parts.to_immutable_buffer()
  63. .aggregate<string>("", (acc, s) => acc + s);
  64. var headers = new Catalogue<string, string>();
  65. headers.add("Content-Type", "application/json");
  66. return new BufferedHttpResult.from_string(
  67. json_string,
  68. StatusCode.OK,
  69. headers
  70. );
  71. });
  72. // User by ID endpoint (simulated)
  73. router.map_func("/users/", (context) => {
  74. var components = context.request.path_components.to_vector();
  75. if (components.count() < 2) {
  76. var headers = new Catalogue<string, string>();
  77. headers.add("Content-Type", "application/json");
  78. return new BufferedHttpResult.from_string(
  79. @"{ \"error\": \"User ID required\" }",
  80. StatusCode.BAD_REQUEST,
  81. headers
  82. );
  83. }
  84. var id_str = components[1];
  85. var id = int.parse(id_str);
  86. // Simulated user lookup
  87. var users = new Series<User>();
  88. users.add(new User(1, "Alice", "alice@example.com"));
  89. users.add(new User(2, "Bob", "bob@example.com"));
  90. users.add(new User(3, "Charlie", "charlie@example.com"));
  91. var user = users.to_immutable_buffer()
  92. .first_or_default(u => u.id == id);
  93. if (user == null) {
  94. var headers = new Catalogue<string, string>();
  95. headers.add("Content-Type", "application/json");
  96. return new BufferedHttpResult.from_string(
  97. @"{ \"error\": \"User not found\" }",
  98. StatusCode.NOT_FOUND,
  99. headers
  100. );
  101. }
  102. var headers = new Catalogue<string, string>();
  103. headers.add("Content-Type", "application/json");
  104. return new BufferedHttpResult.from_string(
  105. user.to_json(),
  106. StatusCode.OK,
  107. headers
  108. );
  109. });
  110. // User posts endpoint (nested path)
  111. router.map_func("/users/", (context) => {
  112. var components = context.request.path_components.to_vector();
  113. // Check for /users/{id}/posts pattern
  114. if (components.count() >= 3 && components[2] == "posts") {
  115. var id_str = components[1];
  116. var id = int.parse(id_str);
  117. // Simulated posts for user
  118. var posts = new Series<Post>();
  119. posts.add(new Post(101, id, "First Post", "This is my first post"));
  120. posts.add(new Post(102, id, "Second Post", "This is my second post"));
  121. var json_parts = new Series<string>();
  122. json_parts.add(@"{ \"user_id\": $id, \"posts\": [");
  123. bool first = true;
  124. posts.to_immutable_buffer().iterate((post) => {
  125. if (!first) json_parts.add(", ");
  126. json_parts.add(post.to_json());
  127. first = false;
  128. });
  129. json_parts.add("] }");
  130. var json_string = json_parts.to_immutable_buffer()
  131. .aggregate<string>("", (acc, s) => acc + s);
  132. var headers = new Catalogue<string, string>();
  133. headers.add("Content-Type", "application/json");
  134. return new BufferedHttpResult.from_string(
  135. json_string,
  136. StatusCode.OK,
  137. headers
  138. );
  139. }
  140. // Fall back to user detail
  141. if (components.count() < 2) {
  142. var headers = new Catalogue<string, string>();
  143. headers.add("Content-Type", "application/json");
  144. return new BufferedHttpResult.from_string(
  145. @"{ \"error\": \"User ID required\" }",
  146. StatusCode.BAD_REQUEST,
  147. headers
  148. );
  149. }
  150. var id_str = components[1];
  151. var id = int.parse(id_str);
  152. var users = new Series<User>();
  153. users.add(new User(1, "Alice", "alice@example.com"));
  154. users.add(new User(2, "Bob", "bob@example.com"));
  155. users.add(new User(3, "Charlie", "charlie@example.com"));
  156. var user = users.to_immutable_buffer()
  157. .first_or_default(u => u.id == id);
  158. if (user == null) {
  159. var headers = new Catalogue<string, string>();
  160. headers.add("Content-Type", "application/json");
  161. return new BufferedHttpResult.from_string(
  162. @"{ \"error\": \"User not found\" }",
  163. StatusCode.NOT_FOUND,
  164. headers
  165. );
  166. }
  167. var headers = new Catalogue<string, string>();
  168. headers.add("Content-Type", "application/json");
  169. return new BufferedHttpResult.from_string(
  170. user.to_json(),
  171. StatusCode.OK,
  172. headers
  173. );
  174. });
  175. // API versioned endpoint
  176. router.map_func("/api/v1/status", (context) => {
  177. var status = new Dictionary<string, string>();
  178. status.set("status", "operational");
  179. status.set("version", "1.0.0");
  180. status.set("timestamp", new DateTime.now_local().format_iso8601());
  181. var json_parts = new Series<string>();
  182. json_parts.add("{ ");
  183. bool first = true;
  184. status.to_immutable_buffer().iterate((kv) => {
  185. if (!first) json_parts.add(", ");
  186. json_parts.add(@"\"$(kv.key)\": \"$(kv.value)\"");
  187. first = false;
  188. });
  189. json_parts.add(" }");
  190. var json_string = json_parts.to_immutable_buffer()
  191. .aggregate<string>("", (acc, s) => acc + s);
  192. var headers = new Catalogue<string, string>();
  193. headers.add("Content-Type", "application/json");
  194. return new BufferedHttpResult.from_string(
  195. json_string,
  196. StatusCode.OK,
  197. headers
  198. );
  199. });
  200. // API items endpoint
  201. router.map_func("/api/v1/items/", (context) => {
  202. var components = context.request.path_components.to_vector();
  203. if (components.count() < 4) {
  204. var headers = new Catalogue<string, string>();
  205. headers.add("Content-Type", "application/json");
  206. return new BufferedHttpResult.from_string(
  207. @"{ \"error\": \"Item ID required\" }",
  208. StatusCode.BAD_REQUEST,
  209. headers
  210. );
  211. }
  212. var id_str = components[3];
  213. var id = int.parse(id_str);
  214. var items = new Dictionary<int, Item>();
  215. items.set(1, new Item(1, "Widget", "A useful widget", 9.99));
  216. items.set(2, new Item(2, "Gadget", "A fancy gadget", 19.99));
  217. items.set(3, new Item(3, "Doohickey", "A mysterious doohickey", 29.99));
  218. Item? item = null;
  219. if (items.try_get(id, out item)) {
  220. var headers = new Catalogue<string, string>();
  221. headers.add("Content-Type", "application/json");
  222. return new BufferedHttpResult.from_string(
  223. item.to_json(),
  224. StatusCode.OK,
  225. headers
  226. );
  227. }
  228. var headers = new Catalogue<string, string>();
  229. headers.add("Content-Type", "application/json");
  230. return new BufferedHttpResult.from_string(
  231. @"{ \"error\": \"Item not found\" }",
  232. StatusCode.NOT_FOUND,
  233. headers
  234. );
  235. });
  236. // Files endpoint with category and name
  237. router.map_func("/files/", (context) => {
  238. var components = context.request.path_components.to_vector();
  239. if (components.count() < 3) {
  240. var headers = new Catalogue<string, string>();
  241. headers.add("Content-Type", "application/json");
  242. return new BufferedHttpResult.from_string(
  243. @"{ \"error\": \"Category and filename required\" }",
  244. StatusCode.BAD_REQUEST,
  245. headers
  246. );
  247. }
  248. var category = components[1];
  249. var name = components[2];
  250. // Simulated file lookup
  251. var files = new Dictionary<string, Dictionary<string, File>>();
  252. var docs = new Dictionary<string, File>();
  253. docs.set("readme.txt", new File("readme.txt", "docs", "This is the readme file"));
  254. docs.set("guide.pdf", new File("guide.pdf", "docs", "User guide"));
  255. var images = new Dictionary<string, File>();
  256. images.set("logo.png", new File("logo.png", "images", "Company logo"));
  257. images.set("banner.jpg", new File("banner.jpg", "images", "Website banner"));
  258. files.set("docs", docs);
  259. files.set("images", images);
  260. Dictionary<string, File>? category_files = null;
  261. if (files.try_get(category, out category_files)) {
  262. File? file = null;
  263. if (category_files.try_get(name, out file)) {
  264. var headers = new Catalogue<string, string>();
  265. headers.add("Content-Type", "application/json");
  266. return new BufferedHttpResult.from_string(
  267. file.to_json(),
  268. StatusCode.OK,
  269. headers
  270. );
  271. }
  272. }
  273. var headers = new Catalogue<string, string>();
  274. headers.add("Content-Type", "application/json");
  275. return new BufferedHttpResult.from_string(
  276. @"{ \"error\": \"File not found in category '$category'\" }",
  277. StatusCode.NOT_FOUND,
  278. headers
  279. );
  280. });
  281. // Path information endpoint - shows all path components
  282. router.map_func("/pathinfo", (context) => {
  283. var parts = new Series<string>();
  284. parts.add("Path Information:\n");
  285. parts.add(@" Raw path: $(context.request.raw_path)\n");
  286. parts.add(@" Path components: $(context.request.path_components.count())\n");
  287. parts.add("\n Components:\n");
  288. context.request.path_components
  289. .with_positions()
  290. .iterate((pair) => {
  291. parts.add(@" [$((int)pair.position)]: $(pair.item)\n");
  292. });
  293. parts.add(@"\n Query string: $(context.request.query_string)\n");
  294. var result = parts.to_immutable_buffer()
  295. .aggregate<string>("", (acc, s) => acc + s);
  296. return new BufferedHttpResult.from_string(result);
  297. });
  298. print("Path Routing Example Server running on port 8082\n");
  299. print("Try these endpoints:\n");
  300. print(" - http://localhost:8082/\n");
  301. print(" - http://localhost:8082/hello\n");
  302. print(" - http://localhost:8082/hello/Alice\n");
  303. print(" - http://localhost:8082/users\n");
  304. print(" - http://localhost:8082/users/1\n");
  305. print(" - http://localhost:8082/users/1/posts\n");
  306. print(" - http://localhost:8082/api/v1/status\n");
  307. print(" - http://localhost:8082/api/v1/items/2\n");
  308. print(" - http://localhost:8082/files/docs/readme.txt\n");
  309. print(" - http://localhost:8082/pathinfo?test=1\n");
  310. server.run();
  311. }
  312. // Helper classes for the example
  313. class User {
  314. public int id { get; private set; }
  315. public string name { get; private set; }
  316. public string email { get; private set; }
  317. public User(int id, string name, string email) {
  318. this.id = id;
  319. this.name = name;
  320. this.email = email;
  321. }
  322. public string to_json() {
  323. return @"{ \"id\": $id, \"name\": \"$name\", \"email\": \"$email\" }";
  324. }
  325. }
  326. class Post {
  327. public int id { get; private set; }
  328. public int user_id { get; private set; }
  329. public string title { get; private set; }
  330. public string content { get; private set; }
  331. public Post(int id, int user_id, string title, string content) {
  332. this.id = id;
  333. this.user_id = user_id;
  334. this.title = title;
  335. this.content = content;
  336. }
  337. public string to_json() {
  338. return @"{ \"id\": $id, \"user_id\": $user_id, \"title\": \"$title\", \"content\": \"$content\" }";
  339. }
  340. }
  341. class Item {
  342. public int id { get; private set; }
  343. public string name { get; private set; }
  344. public string description { get; private set; }
  345. public double price { get; private set; }
  346. public Item(int id, string name, string description, double price) {
  347. this.id = id;
  348. this.name = name;
  349. this.description = description;
  350. this.price = price;
  351. }
  352. public string to_json() {
  353. return @"{ \"id\": $id, \"name\": \"$name\", \"description\": \"$description\", \"price\": $price }";
  354. }
  355. }
  356. class File {
  357. public string name { get; private set; }
  358. public string category { get; private set; }
  359. public string description { get; private set; }
  360. public File(string name, string category, string description) {
  361. this.name = name;
  362. this.category = category;
  363. this.description = description;
  364. }
  365. public string to_json() {
  366. return @"{ \"name\": \"$name\", \"category\": \"$category\", \"description\": \"$description\" }";
  367. }
  368. }