example_router_vars.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* _
  2. * ___ __ _ __ _ _ _(_)
  3. * / __|/ _` |/ _` | | | | |
  4. * \__ \ (_| | (_| | |_| | |
  5. * |___/\__,_|\__, |\__,_|_|
  6. * |___/
  7. *
  8. * Cross-platform library which helps to develop web servers or frameworks.
  9. *
  10. * Copyright (C) 2016-2019 Silvio Clecio <[email protected]>
  11. *
  12. * Sagui library is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU Lesser General Public
  14. * License as published by the Free Software Foundation; either
  15. * version 2.1 of the License, or (at your option) any later version.
  16. *
  17. * Sagui library is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. * Lesser General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Lesser General Public
  23. * License along with Sagui library; if not, write to the Free Software
  24. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25. */
  26. #include <stdlib.h>
  27. #include <stdio.h>
  28. #include <sagui.h>
  29. /* NOTE: Error checking has been omitted to make it clear. */
  30. static int vars_iter_cb(__SG_UNUSED void *cls, const char *name,
  31. const char *val) {
  32. fprintf(stdout, " %s: %s\n", name, val);
  33. return 0;
  34. }
  35. static void route_cb(void *cls, struct sg_route *route) {
  36. fprintf(stdout, "%s: %s\n", sg_route_path(route), (const char *) cls);
  37. sg_route_vars_iter(route, vars_iter_cb, NULL);
  38. }
  39. int main(void) {
  40. struct sg_router *router;
  41. struct sg_route *routes = NULL;
  42. sg_routes_add(&routes, "/foo/bar", route_cb, "foo-bar-data");
  43. sg_routes_add(&routes, "/bar", route_cb, "bar-data");
  44. sg_routes_add(&routes, "/customer/(?P<name>[a-zA-Z]+)", route_cb,
  45. "customer-data");
  46. sg_routes_add(&routes, "/product/(?P<id>[0-9]+)", route_cb, "product-data");
  47. sg_routes_add(&routes, "/employee/(?P<id>[0-9]+)/[a|i]", route_cb,
  48. "employee-data");
  49. router = sg_router_new(routes);
  50. sg_router_dispatch(router, "/foo/bar", NULL);
  51. fprintf(stdout, "---\n");
  52. sg_router_dispatch(router, "/customer/Torvalds", NULL);
  53. fprintf(stdout, "---\n");
  54. sg_router_dispatch(router, "/product/123", NULL);
  55. fprintf(stdout, "---\n");
  56. sg_router_dispatch(router, "/employee/123/i", NULL);
  57. sg_routes_cleanup(&routes);
  58. sg_router_free(router);
  59. fflush(stdout);
  60. return EXIT_SUCCESS;
  61. }