example_httpreq_form.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* _
  2. * ___ __ _ __ _ _ _(_)
  3. * / __|/ _` |/ _` | | | | |
  4. * \__ \ (_| | (_| | |_| | |
  5. * |___/\__,_|\__, |\__,_|_|
  6. * |___/
  7. *
  8. * Cross-platform library which helps to develop web servers or frameworks.
  9. *
  10. * Copyright (C) 2016-2021 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. * Sending HTML form fields using cURL:
  28. *
  29. * curl --request POST --data 'username=silvioprog&password=i-love-sagui' -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_strmap **fields = sg_httpreq_fields(req);
  40. struct sg_str *result = sg_str_new();
  41. const char *username = sg_strmap_get(*fields, "username");
  42. const char *password = sg_strmap_get(*fields, "password");
  43. sg_str_printf(result, "Username: %s; Password: %s", username, password);
  44. sg_httpres_send(res, sg_str_content(result), "text/plain", 200);
  45. sg_str_free(result);
  46. }
  47. int main(int argc, const char *argv[]) {
  48. struct sg_httpsrv *srv;
  49. uint16_t port;
  50. if (argc != 2) {
  51. printf("%s <PORT>\n", argv[0]);
  52. return EXIT_FAILURE;
  53. }
  54. port = strtol(argv[1], NULL, 10);
  55. srv = sg_httpsrv_new(req_cb, NULL);
  56. if (!sg_httpsrv_listen(srv, port, false)) {
  57. sg_httpsrv_free(srv);
  58. return EXIT_FAILURE;
  59. }
  60. fprintf(stdout, "Server running at http://localhost:%d\n",
  61. sg_httpsrv_port(srv));
  62. fflush(stdout);
  63. getchar();
  64. sg_httpsrv_free(srv);
  65. return EXIT_SUCCESS;
  66. }