PathRouting.vala 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 the Router's named segment feature for dynamic routing.
  9. */
  10. // Root handler - shows available endpoints
  11. class RootHandler : Object, RouteHandler {
  12. public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
  13. return new HttpStringResult("""Welcome to the Path Routing Example!
  14. Available endpoints:
  15. GET / - This message
  16. GET /hello - Simple greeting
  17. GET /hello/{name} - Greeting with name
  18. GET /users - List all users
  19. GET /users/{id} - Get user by ID
  20. GET /users/{id}/posts - Get posts for a user
  21. GET /api/v1/status - API status
  22. GET /api/v1/items/{id} - Get item by ID
  23. GET /files/{category}/{name} - Get file by category and name
  24. GET /pathinfo - Path information demo
  25. """);
  26. }
  27. }
  28. // Simple hello handler
  29. class HelloHandler : Object, RouteHandler {
  30. public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
  31. return new HttpStringResult("Hello, World!");
  32. }
  33. }
  34. // Hello with name handler - uses named segment
  35. class HelloNameHandler : Object, RouteHandler {
  36. public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
  37. var name = route_context.get_segment("name");
  38. return new HttpStringResult(@"Hello, $name!");
  39. }
  40. }
  41. // Users list handler
  42. class UsersHandler : Object, RouteHandler {
  43. public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
  44. var users = new Series<User>();
  45. users.add(new User(1, "Alice", "alice@example.com"));
  46. users.add(new User(2, "Bob", "bob@example.com"));
  47. users.add(new User(3, "Charlie", "charlie@example.com"));
  48. var json_parts = new Series<string>();
  49. json_parts.add(@"{ \"users\": [");
  50. bool first = true;
  51. users.to_immutable_buffer().iterate((user) => {
  52. if (!first) json_parts.add(", ");
  53. json_parts.add(user.to_json());
  54. first = false;
  55. });
  56. json_parts.add("] }");
  57. var json_string = json_parts.to_immutable_buffer()
  58. .aggregate<string>("", (acc, s) => acc + s);
  59. return new HttpStringResult(json_string)
  60. .set_header("Content-Type", "application/json");
  61. }
  62. }
  63. // User by ID handler - uses named segment
  64. class UserByIdHandler : Object, RouteHandler {
  65. public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
  66. var id_str = route_context.get_segment("id");
  67. var id = int.parse(id_str);
  68. // Simulated user lookup
  69. var users = new Series<User>();
  70. users.add(new User(1, "Alice", "alice@example.com"));
  71. users.add(new User(2, "Bob", "bob@example.com"));
  72. users.add(new User(3, "Charlie", "charlie@example.com"));
  73. var user = users.to_immutable_buffer()
  74. .first_or_default(u => u.id == id);
  75. if (user == null) {
  76. return new HttpStringResult(@"{ \"error\": \"User not found\" }")
  77. .set_header("Content-Type", "application/json");
  78. }
  79. return new HttpStringResult(user.to_json())
  80. .set_header("Content-Type", "application/json");
  81. }
  82. }
  83. // User posts handler - uses named segment
  84. class UserPostsHandler : Object, RouteHandler {
  85. public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
  86. var id_str = route_context.get_segment("id");
  87. var id = int.parse(id_str);
  88. // Simulated posts for user
  89. var posts = new Series<Post>();
  90. posts.add(new Post(101, id, "First Post", "This is my first post"));
  91. posts.add(new Post(102, id, "Second Post", "This is my second post"));
  92. var json_parts = new Series<string>();
  93. json_parts.add(@"{ \"user_id\": $id, \"posts\": [");
  94. bool first = true;
  95. posts.to_immutable_buffer().iterate((post) => {
  96. if (!first) json_parts.add(", ");
  97. json_parts.add(post.to_json());
  98. first = false;
  99. });
  100. json_parts.add("] }");
  101. var json_string = json_parts.to_immutable_buffer()
  102. .aggregate<string>("", (acc, s) => acc + s);
  103. return new HttpStringResult(json_string)
  104. .set_header("Content-Type", "application/json");
  105. }
  106. }
  107. // API status handler
  108. class ApiStatusHandler : Object, RouteHandler {
  109. public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
  110. var status = new Dictionary<string, string>();
  111. status.set("status", "operational");
  112. status.set("version", "1.0.0");
  113. status.set("timestamp", new DateTime.now_local().format_iso8601());
  114. var json_parts = new Series<string>();
  115. json_parts.add("{ ");
  116. bool first = true;
  117. status.to_immutable_buffer().iterate((kv) => {
  118. if (!first) json_parts.add(", ");
  119. json_parts.add(@"\"$(kv.key)\": \"$(kv.value)\"");
  120. first = false;
  121. });
  122. json_parts.add(" }");
  123. var json_string = json_parts.to_immutable_buffer()
  124. .aggregate<string>("", (acc, s) => acc + s);
  125. return new HttpStringResult(json_string)
  126. .set_header("Content-Type", "application/json");
  127. }
  128. }
  129. // API item handler - uses named segment
  130. class ApiItemHandler : Object, RouteHandler {
  131. public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
  132. var id_str = route_context.get_segment("id");
  133. var id = int.parse(id_str);
  134. var items = new Dictionary<int, Item>();
  135. items.set(1, new Item(1, "Widget", "A useful widget", 9.99));
  136. items.set(2, new Item(2, "Gadget", "A fancy gadget", 19.99));
  137. items.set(3, new Item(3, "Doohickey", "A mysterious doohickey", 29.99));
  138. Item? item = null;
  139. if (items.try_get(id, out item)) {
  140. return new HttpStringResult(item.to_json())
  141. .set_header("Content-Type", "application/json");
  142. }
  143. return new HttpStringResult(@"{ \"error\": \"Item not found\" }")
  144. .set_header("Content-Type", "application/json");
  145. }
  146. }
  147. // Files handler - uses two named segments
  148. class FilesHandler : Object, RouteHandler {
  149. public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
  150. var category = route_context.get_segment("category");
  151. var name = route_context.get_segment("name");
  152. // Simulated file lookup
  153. var files = new Dictionary<string, Dictionary<string, ExampleFile>>();
  154. var docs = new Dictionary<string, ExampleFile>();
  155. docs.set("readme.txt", new ExampleFile("readme.txt", "docs", "This is the readme file"));
  156. docs.set("guide.pdf", new ExampleFile("guide.pdf", "docs", "User guide"));
  157. var images = new Dictionary<string, ExampleFile>();
  158. images.set("logo.png", new ExampleFile("logo.png", "images", "Company logo"));
  159. images.set("banner.jpg", new ExampleFile("banner.jpg", "images", "Website banner"));
  160. files.set("docs", docs);
  161. files.set("images", images);
  162. Dictionary<string, ExampleFile>? category_files = null;
  163. if (files.try_get(category, out category_files)) {
  164. ExampleFile? file = null;
  165. if (category_files.try_get(name, out file)) {
  166. return new HttpStringResult(file.to_json())
  167. .set_header("Content-Type", "application/json");
  168. }
  169. }
  170. return new HttpStringResult(@"{ \"error\": \"File not found in category '$category'\" }")
  171. .set_header("Content-Type", "application/json");
  172. }
  173. }
  174. // Path info handler
  175. class PathInfoHandler : Object, RouteHandler {
  176. public async HttpResult handle_route(HttpContext http_context, RouteContext route_context) throws Error {
  177. var parts = new Series<string>();
  178. parts.add("Path Information:\n");
  179. parts.add(@" Raw path: $(http_context.request.raw_path)\n");
  180. parts.add(@" Path components: $(http_context.request.path_components.count())\n");
  181. parts.add("\n Components:\n");
  182. http_context.request.path_components
  183. .with_positions()
  184. .iterate((pair) => {
  185. parts.add(@" [$((int)pair.position)]: $(pair.item)\n");
  186. });
  187. parts.add(@"\n Query string: $(http_context.request.query_string)\n");
  188. // Show named segments from route context
  189. parts.add("\n Named segments:\n");
  190. route_context.named_segments.to_immutable_buffer()
  191. .iterate((kv) => {
  192. parts.add(@" $(kv.key): $(kv.value)\n");
  193. });
  194. var result = parts.to_immutable_buffer()
  195. .aggregate<string>("", (acc, s) => acc + s);
  196. return new HttpStringResult(result);
  197. }
  198. }
  199. void main() {
  200. var router = new Router();
  201. var server = new Server(8082, router);
  202. // Register routes with named segments
  203. router.get("/", new RootHandler());
  204. router.get("/hello", new HelloHandler());
  205. router.get("/hello/{name}", new HelloNameHandler());
  206. router.get("/users", new UsersHandler());
  207. router.get("/users/{id}", new UserByIdHandler());
  208. router.get("/users/{id}/posts", new UserPostsHandler());
  209. router.get("/api/v1/status", new ApiStatusHandler());
  210. router.get("/api/v1/items/{id}", new ApiItemHandler());
  211. router.get("/files/{category}/{name}", new FilesHandler());
  212. router.get("/pathinfo", new PathInfoHandler());
  213. print("Path Routing Example Server running on port 8082\n");
  214. print("Try these endpoints:\n");
  215. print(" - http://localhost:8082/\n");
  216. print(" - http://localhost:8082/hello\n");
  217. print(" - http://localhost:8082/hello/Alice\n");
  218. print(" - http://localhost:8082/users\n");
  219. print(" - http://localhost:8082/users/1\n");
  220. print(" - http://localhost:8082/users/1/posts\n");
  221. print(" - http://localhost:8082/api/v1/status\n");
  222. print(" - http://localhost:8082/api/v1/items/2\n");
  223. print(" - http://localhost:8082/files/docs/readme.txt\n");
  224. print(" - http://localhost:8082/pathinfo?test=1\n");
  225. server.run();
  226. }
  227. // Helper classes for the example
  228. class User {
  229. public int id { get; private set; }
  230. public string name { get; private set; }
  231. public string email { get; private set; }
  232. public User(int id, string name, string email) {
  233. this.id = id;
  234. this.name = name;
  235. this.email = email;
  236. }
  237. public string to_json() {
  238. return @"{ \"id\": $id, \"name\": \"$name\", \"email\": \"$email\" }";
  239. }
  240. }
  241. class Post {
  242. public int id { get; private set; }
  243. public int user_id { get; private set; }
  244. public string title { get; private set; }
  245. public string content { get; private set; }
  246. public Post(int id, int user_id, string title, string content) {
  247. this.id = id;
  248. this.user_id = user_id;
  249. this.title = title;
  250. this.content = content;
  251. }
  252. public string to_json() {
  253. return @"{ \"id\": $id, \"user_id\": $user_id, \"title\": \"$title\", \"content\": \"$content\" }";
  254. }
  255. }
  256. class Item {
  257. public int id { get; private set; }
  258. public string name { get; private set; }
  259. public string description { get; private set; }
  260. public double price { get; private set; }
  261. public Item(int id, string name, string description, double price) {
  262. this.id = id;
  263. this.name = name;
  264. this.description = description;
  265. this.price = price;
  266. }
  267. public string to_json() {
  268. return @"{ \"id\": $id, \"name\": \"$name\", \"description\": \"$description\", \"price\": $price }";
  269. }
  270. }
  271. class ExampleFile {
  272. public string name { get; private set; }
  273. public string category { get; private set; }
  274. public string description { get; private set; }
  275. public ExampleFile(string name, string category, string description) {
  276. this.name = name;
  277. this.category = category;
  278. this.description = description;
  279. }
  280. public string to_json() {
  281. return @"{ \"name\": \"$name\", \"category\": \"$category\", \"description\": \"$description\" }";
  282. }
  283. }