From 8428f362c1709777ad41c698c94ead53834c9e7b Mon Sep 17 00:00:00 2001 From: Sergey Lyubka Date: Fri, 31 Aug 2012 09:24:34 +0100 Subject: [PATCH] Added example for handling POST requests. --- examples/Makefile | 1 + examples/post.c | 61 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 examples/post.c diff --git a/examples/Makefile b/examples/Makefile index 46691e31..d8a67488 100644 --- a/examples/Makefile +++ b/examples/Makefile @@ -4,4 +4,5 @@ all: OS=`uname`; \ test "$$OS" = Linux && LIBS="-ldl" ; \ $(CC) $(CFLAGS) hello.c ../mongoose.c $$LIBS $(ADD) -o hello; + $(CC) $(CFLAGS) post.c ../mongoose.c $$LIBS $(ADD) -o post; $(CC) $(CFLAGS) chat.c ../mongoose.c $$LIBS $(ADD) -o chat diff --git a/examples/post.c b/examples/post.c new file mode 100644 index 00000000..f30cc0ee --- /dev/null +++ b/examples/post.c @@ -0,0 +1,61 @@ +#include +#include +#include "mongoose.h" + +static const char *html_form = + "POST example." + "
" + "Input 1:
" + "Input 2:
" + "" + "
"; + +static void *callback(enum mg_event event, + struct mg_connection *conn) { + const struct mg_request_info *ri = mg_get_request_info(conn); + + if (event == MG_NEW_REQUEST) { + if (!strcmp(ri->uri, "/handle_post_request")) { + // User has submitted a form, show submitted data and a variable value + char post_data[1024], + input1[sizeof(post_data)], input2[sizeof(post_data)]; + int post_data_len; + + // Read POST data + post_data_len = mg_read(conn, post_data, sizeof(post_data)); + + // Parse form data. input1 and input2 are guaranteed to be NUL-terminated + mg_get_var(post_data, post_data_len, "input_1", input1, sizeof(input1)); + mg_get_var(post_data, post_data_len, "input_2", input2, sizeof(input2)); + + mg_printf(conn, "HTTP/1.0 200 OK\r\n" + "Content-Type: text/plain\r\n\r\n" + "Submitted data: [%.*s]\n" + "Submitted data length: %d bytes\n" + "input_1: [%s]\n" + "input_2: [%s]\n", + post_data_len, post_data, post_data_len, input1, input2); + } else { + // Show HTML form. + mg_printf(conn, "HTTP/1.0 200 OK\r\n" + "Content-Length: %d\r\n" + "Content-Type: text/html\r\n\r\n%s", + (int) strlen(html_form), html_form); + } + // Mark as processed + return ""; + } else { + return NULL; + } +} + +int main(void) { + struct mg_context *ctx; + const char *options[] = {"listening_ports", "8080", NULL}; + + ctx = mg_start(&callback, NULL, options); + getchar(); // Wait until user hits "enter" + mg_stop(ctx); + + return 0; +}