PathRouting.vala 14 KB

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