example_httpreq_payload.c 2.1 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. /*
  27. * Echoing payload using cURL:
  28. *
  29. * curl --header "Content-Type: application/json" --request POST --data '{"abc":123}' -w "\n" http://localhost:<PORT>
  30. */
  31. #include <stdio.h>
  32. #include <stdlib.h>
  33. #include <stdint.h>
  34. #include <string.h>
  35. #include <sagui.h>
  36. /* NOTE: Error checking has been omitted to make it clear. */
  37. static void req_cb(__SG_UNUSED void *cls, struct sg_httpreq *req,
  38. struct sg_httpres *res) {
  39. struct sg_str *payload = sg_httpreq_payload(req);
  40. sg_httpres_send(res, sg_str_content(payload), "text/plain", 200);
  41. }
  42. int main(int argc, const char *argv[]) {
  43. struct sg_httpsrv *srv;
  44. uint16_t port;
  45. if (argc != 2) {
  46. printf("%s <PORT>\n", argv[0]);
  47. return EXIT_FAILURE;
  48. }
  49. port = strtol(argv[1], NULL, 10);
  50. srv = sg_httpsrv_new(req_cb, NULL);
  51. if (!sg_httpsrv_listen(srv, port, false)) {
  52. sg_httpsrv_free(srv);
  53. return EXIT_FAILURE;
  54. }
  55. fprintf(stdout, "Server running at http://localhost:%d\n",
  56. sg_httpsrv_port(srv));
  57. fflush(stdout);
  58. getchar();
  59. sg_httpsrv_free(srv);
  60. return EXIT_SUCCESS;
  61. }