Router.vala 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using Invercargill.DataStructures;
  2. namespace Astralis {
  3. public delegate HttpResult RouteHandler(HttpContext context) throws Error;
  4. public class RouteEntry {
  5. public RouteHandler handler;
  6. public RouteEntry(owned RouteHandler handler) {
  7. this.handler = (owned) handler;
  8. }
  9. }
  10. public class Router : HttpHandler, Object {
  11. private Dictionary<string, RouteEntry> routes = new Dictionary<string, RouteEntry>();
  12. public void map_get(string path, owned RouteHandler handler) {
  13. // In a real router, we'd handle methods separately.
  14. // For now, simple path mapping.
  15. routes.set(path, new RouteEntry((owned) handler));
  16. }
  17. public async HttpResult handle(HttpContext context) {
  18. try {
  19. return routes.get(context.request.raw_path).handler(context);
  20. } catch (Invercargill.IndexError e) {
  21. return new BufferedHttpResult.from_string("Not Found", StatusCode.NOT_FOUND);
  22. }
  23. catch {
  24. return new BufferedHttpResult.from_string("Internal Server Error", StatusCode.INTERNAL_SERVER_ERROR);
  25. }
  26. }
  27. }
  28. }