example_httpsrv.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 <stdio.h>
  27. #include <stdlib.h>
  28. #include <stdint.h>
  29. #include <unistd.h>
  30. #include <signal.h>
  31. #include <sagui.h>
  32. /* NOTE: Error checking has been omitted to make it clear. */
  33. static bool terminated = false;
  34. static void sig_handler(__SG_UNUSED int signum) {
  35. terminated = true;
  36. }
  37. static void req_cb(__SG_UNUSED void *cls, __SG_UNUSED struct sg_httpreq *req,
  38. struct sg_httpres *res) {
  39. sg_httpres_send(res,
  40. "<html><head><title>Hello world</title></head><body>Hello "
  41. "world</body></html>",
  42. "text/html; charset=utf-8", 200);
  43. }
  44. int main(int argc, const char *argv[]) {
  45. struct sg_httpsrv *srv;
  46. uint16_t port;
  47. if (argc != 2) {
  48. printf("%s <PORT>\n", argv[0]);
  49. return EXIT_FAILURE;
  50. }
  51. signal(SIGTERM, sig_handler);
  52. signal(SIGINT, sig_handler);
  53. port = strtol(argv[1], NULL, 10);
  54. srv = sg_httpsrv_new(req_cb, NULL);
  55. if (!sg_httpsrv_listen(srv, port, false)) {
  56. sg_httpsrv_free(srv);
  57. return EXIT_FAILURE;
  58. }
  59. fprintf(stdout, "Server running at http://localhost:%d\n",
  60. sg_httpsrv_port(srv));
  61. fflush(stdout);
  62. while (!terminated) {
  63. usleep(100 * 1000);
  64. }
  65. sg_httpsrv_free(srv);
  66. return EXIT_SUCCESS;
  67. }