post.c 2.0 KB

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