post.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include "civetweb.h"
  4. static const char *html_form =
  5. "<html><body>POST example."
  6. "<form method=\"POST\" action=\"/handle_post_request\">"
  7. "Input 1: <input type=\"text\" name=\"input_1\" /> <br/>"
  8. "Input 2: <input type=\"text\" name=\"input_2\" /> <br/>"
  9. "<input type=\"submit\" />"
  10. "</form></body></html>";
  11. static int begin_request_handler(struct mg_connection *conn)
  12. {
  13. const struct mg_request_info *ri = mg_get_request_info(conn);
  14. char post_data[1024], input1[sizeof(post_data)], input2[sizeof(post_data)];
  15. int post_data_len;
  16. if (!strcmp(ri->uri, "/handle_post_request")) {
  17. // User has submitted a form, show submitted data and a variable value
  18. post_data_len = mg_read(conn, post_data, sizeof(post_data));
  19. // Parse form data. input1 and input2 are guaranteed to be NUL-terminated
  20. mg_get_var(post_data, post_data_len, "input_1", input1, sizeof(input1));
  21. mg_get_var(post_data, post_data_len, "input_2", input2, sizeof(input2));
  22. // Send reply to the client, showing submitted form values.
  23. mg_printf(conn, "HTTP/1.0 200 OK\r\n"
  24. "Content-Type: text/plain\r\n\r\n"
  25. "Submitted data: [%.*s]\n"
  26. "Submitted data length: %d bytes\n"
  27. "input_1: [%s]\n"
  28. "input_2: [%s]\n",
  29. post_data_len, post_data, post_data_len, input1, input2);
  30. } else {
  31. // Show HTML form.
  32. mg_printf(conn, "HTTP/1.0 200 OK\r\n"
  33. "Content-Length: %d\r\n"
  34. "Content-Type: text/html\r\n\r\n%s",
  35. (int) strlen(html_form), html_form);
  36. }
  37. return 1; // Mark request as processed
  38. }
  39. int main(void)
  40. {
  41. struct mg_context *ctx;
  42. const char *options[] = {"listening_ports", "8080", NULL};
  43. struct mg_callbacks callbacks;
  44. memset(&callbacks, 0, sizeof(callbacks));
  45. callbacks.begin_request = begin_request_handler;
  46. ctx = mg_start(&callbacks, NULL, options);
  47. getchar(); // Wait until user hits "enter"
  48. mg_stop(ctx);
  49. return 0;
  50. }