example_httpcomp.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 <stdint.h>
  28. #include <sagui.h>
  29. /* NOTE: Error checking has been omitted to make it clear. */
  30. #define PAGE \
  31. "<html><head><title>Hello world</title></head><body>Hello " \
  32. "world</body></html>"
  33. #define CONTENT_TYPE "text/html; charset=utf-8"
  34. static void req_cb(__SG_UNUSED void *cls, struct sg_httpreq *req,
  35. struct sg_httpres *res) {
  36. struct sg_strmap **headers;
  37. const char *header;
  38. headers = sg_httpreq_headers(req);
  39. if (headers) {
  40. header = sg_strmap_get(*headers, "Accept-Encoding");
  41. if (header && strstr(header, "deflate")) {
  42. sg_httpres_zsendbinary(res, PAGE, strlen(PAGE), CONTENT_TYPE, 200);
  43. return;
  44. }
  45. }
  46. sg_httpres_sendbinary(res, PAGE, strlen(PAGE), CONTENT_TYPE, 200);
  47. }
  48. int main(int argc, const char *argv[]) {
  49. struct sg_httpsrv *srv;
  50. uint16_t port;
  51. if (argc != 2) {
  52. printf("%s <PORT>\n", argv[0]);
  53. return EXIT_FAILURE;
  54. }
  55. port = strtol(argv[1], NULL, 10);
  56. srv = sg_httpsrv_new(req_cb, NULL);
  57. if (!sg_httpsrv_listen(srv, port, false)) {
  58. sg_httpsrv_free(srv);
  59. return EXIT_FAILURE;
  60. }
  61. fprintf(stdout, "Server running at http://localhost:%d\n",
  62. sg_httpsrv_port(srv));
  63. fflush(stdout);
  64. getchar();
  65. sg_httpsrv_free(srv);
  66. return EXIT_SUCCESS;
  67. }