example_httpreq_isolate.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* _
  2. * ___ __ _ __ _ _ _(_)
  3. * / __|/ _` |/ _` | | | | |
  4. * \__ \ (_| | (_| | |_| | |
  5. * |___/\__,_|\__, |\__,_|_|
  6. * |___/
  7. *
  8. * Cross-platform library which helps to develop web servers or frameworks.
  9. *
  10. * Copyright (C) 2016-2020 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 <stdio.h>
  27. #include <stdlib.h>
  28. #include <stdint.h>
  29. #include <string.h>
  30. #include <unistd.h>
  31. #include <sagui.h>
  32. /* NOTE: Error checking has been omitted to make it clear. */
  33. static void req_isolated_cb(__SG_UNUSED void *cls,
  34. __SG_UNUSED struct sg_httpreq *req,
  35. struct sg_httpres *res) {
  36. sleep(3);
  37. sg_httpres_send(
  38. res,
  39. "<html><head><title>Isolated request</title></head><body>Isolated and "
  40. "delayed request</body></html>",
  41. "text/html; charset=utf-8", 200);
  42. }
  43. static void req_cb(__SG_UNUSED void *cls, struct sg_httpreq *req,
  44. struct sg_httpres *res) {
  45. if (strcmp(sg_httpreq_path(req), "/delayed") == 0)
  46. sg_httpreq_isolate(req, req_isolated_cb, NULL);
  47. else
  48. sg_httpres_send(res,
  49. "<html><head><title>Hello world</title></head><body>Hello "
  50. "world</body></html>",
  51. "text/html; charset=utf-8", 200);
  52. }
  53. int main(int argc, const char *argv[]) {
  54. struct sg_httpsrv *srv;
  55. uint16_t port;
  56. if (argc != 2) {
  57. printf("%s <PORT>\n", argv[0]);
  58. return EXIT_FAILURE;
  59. }
  60. port = strtol(argv[1], NULL, 10);
  61. srv = sg_httpsrv_new(req_cb, NULL);
  62. if (!sg_httpsrv_listen(srv, port, false)) {
  63. sg_httpsrv_free(srv);
  64. return EXIT_FAILURE;
  65. }
  66. fprintf(stdout, "Server running at http://localhost:%d\n",
  67. sg_httpsrv_port(srv));
  68. fflush(stdout);
  69. getchar();
  70. sg_httpsrv_free(srv);
  71. return EXIT_SUCCESS;
  72. }