最近在学数据库、网络编程,干脆两者结合搞个小练习,看看以后怎么拓展一下吧
httpServer 用 mongoose 实现, 4000左右httpserver的基本功能全都有
#include <stdio.h>
#include <string.h>
#include "mongoose.h"
#include "mysql.h"
static const char *html_form =
"<html><body>POST example."
"<form method=\"POST\" action=\"/handle_post_request\">"
"Input 1: <input type=\"text\" name=\"input_1\" /> <br/>"
"Input 2: <input type=\"text\" name=\"input_2\" /> <br/>"
"<input type=\"submit\" />"
"</form></body></html>";
MYSQL *conn_ptr;
MYSQL_RES *result;
MYSQL_ROW row;
int check_password(char *usrname, char *psswd)
{
mysql_query(conn_ptr, "SELECT ID,password FROM reg");
result = mysql_store_result(conn_ptr);
while((row = mysql_fetch_row(result))) {
if (!strcmp(usrname, row[0]) && !strcmp(psswd, row[1])) {
return 1;
}
}
return 0;
}
static void send_reply(struct mg_connection *conn) {
char var1[500], var2[500];
if (strcmp(conn->uri, "/handle_post_request") == 0) {
// User has submitted a form, show submitted data and a variable value
// Parse form data. var1 and var2 are guaranteed to be NUL-terminated
mg_get_var(conn, "input_1", var1, sizeof(var1));
mg_get_var(conn, "input_2", var2, sizeof(var2));
if (check_password(var1, var2)) {
mg_send_header(conn, "Content-Type", "text/plain");
mg_printf_data(conn, "login !");
} else {
mg_send_header(conn, "Content-Type", "text/plain");
mg_printf_data(conn, "failed!");
}
} else {
// Show HTML form.
mg_send_data(conn, html_form, strlen(html_form));
}
}
static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
if (ev == MG_REQUEST) {
send_reply(conn);
return MG_TRUE;
} else if (ev == MG_AUTH) {
return MG_TRUE;
} else {
return MG_FALSE;
}
}
int main(void) {
conn_ptr = mysql_init(NULL);
conn_ptr = mysql_real_connect(conn_ptr, "localhost",
"root", "Wayne265", "LetsChat", 0, NULL, 0);
struct mg_server *server = mg_create_server(NULL, ev_handler);
mg_set_option(server, "listening_port", "8000");
printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
for (;;) {
mg_poll_server(server, 1000);
}
mg_destroy_server(&server);
return 0;
}