post.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include "mongoose.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 void *callback(enum mg_event event,
  12. struct mg_connection *conn) {
  13. const struct mg_request_info *ri = mg_get_request_info(conn);
  14. if (event == MG_NEW_REQUEST) {
  15. if (!strcmp(ri->uri, "/handle_post_request")) {
  16. // User has submitted a form, show submitted data and a variable value
  17. char post_data[1024],
  18. input1[sizeof(post_data)], input2[sizeof(post_data)];
  19. int post_data_len;
  20. // Read POST data
  21. post_data_len = mg_read(conn, post_data, sizeof(post_data));
  22. // Parse form data. input1 and input2 are guaranteed to be NUL-terminated
  23. mg_get_var(post_data, post_data_len, "input_1", input1, sizeof(input1));
  24. mg_get_var(post_data, post_data_len, "input_2", input2, sizeof(input2));
  25. mg_printf(conn, "HTTP/1.0 200 OK\r\n"
  26. "Content-Type: text/plain\r\n\r\n"
  27. "Submitted data: [%.*s]\n"
  28. "Submitted data length: %d bytes\n"
  29. "input_1: [%s]\n"
  30. "input_2: [%s]\n",
  31. post_data_len, post_data, post_data_len, input1, input2);
  32. } else {
  33. // Show HTML form.
  34. mg_printf(conn, "HTTP/1.0 200 OK\r\n"
  35. "Content-Length: %d\r\n"
  36. "Content-Type: text/html\r\n\r\n%s",
  37. (int) strlen(html_form), html_form);
  38. }
  39. // Mark as processed
  40. return "";
  41. } else {
  42. return NULL;
  43. }
  44. }
  45. int main(void) {
  46. struct mg_context *ctx;
  47. const char *options[] = {"listening_ports", "8080", NULL};
  48. ctx = mg_start(&callback, NULL, options);
  49. getchar(); // Wait until user hits "enter"
  50. mg_stop(ctx);
  51. return 0;
  52. }