PathRouting.vala 14 KB

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