c++ - mongoose web server helloworld program -
i came across embedded web server named mongoose , http://code.google.com/p/mongoose/ , read wiki great , searched sample hello world program couldn't find it... found example written in c++ windows , can 1 provide example c program run webserver..
it quite simple, first need implement call function:
void *event_handler(enum mg_event event, struct mg_connection *conn) { const struct mg_request_info *request_info = mg_get_request_info(conn); static void* done = "done"; if (event == mg_new_request) { if (strcmp(request_info->uri, "/hello") == 0) { // handle c[renderer] request if(strcmp(request_info->request_method, "get") != 0) { // send error (we care http get) mg_printf(conn, "http/1.1 %d error (%s)\r\n\r\n%s", 500, "we care http get", "we care http get"); // return not null means handled request return done; } // handle request /hello char* content = "hello world!"; char* mimetype = "text/plain"; int contentlength = strlen(content); mg_printf(conn, "http/1.1 200 ok\r\n" "cache: no-cache\r\n" "content-type: %s\r\n" "content-length: %d\r\n" "\r\n", mimetype, contentlength); mg_write(conn, content, contentlength); return done; } } // in example handle /hello mg_printf(conn, "http/1.1 %d error (%s)\r\n\r\n%s", 500, /* error code want send back*/ "invalid request.", "invalid request."); return done; } // no suitable handler found, mark not processed. mongoose // try serve request. return null; }
then need start server:
int main(int argc, char **argv) { /* default options http server */ const char *options[] = { "listening_ports", "8081", "num_threads", "10", null }; /* initialize http layer */ static struct mg_context *ctx; ctx = mg_start(&event_handler, options); if(ctx == null) { exit(exit_failure); } puts("server running, press enter exit\n"); getchar(); mg_stop(ctx); return exit_success; }
Comments
Post a Comment