1. The need to use c ++ http provide services, I had wanted to use libevent, but after some searching, found only two references mongoose library file.
The official document: https://cesanta.com/docs/overview/intro.html
Official Code: https://github.com/cesanta/mongoose
2. The relevant code
#include "HttpService.h"
struct mg_serve_http_opts HttpService::s_http_server_opts;
//请求事件处理
void HttpService::mgEvHandler(struct mg_connection *nc, int ev, void *p) {
//处理request
if (ev == MG_EV_HTTP_REQUEST) {
struct http_message *msg = (struct http_message *)p;
//body内容
char* body = new char[msg->body.len + 1];
memset(body, 0, Msg-> + body.len . 1 );
the memcpy (body, MSG -> body.p, msg-> body.len);
// URI content
char * URI = new new char [msg-> uri.len + . 1 ] ;
Memset (URI, 0 , msg-> + uri.len . 1 );
the memcpy (URI, MSG -> uri.p, msg-> uri.len);
// return body information
mgSendBody (NC, " body Content " ) ;
// returns download file
// mgSendFile ( "path relative to the s_http_server_opts.document_root");
Delete URI;
Delete body;
}
}
// Send message body
void the HttpService :: mgSendBody ( struct mg_connection NC *, const char * Content) {
mg_send_head (NC, 200 is , strlen (Content), " the Content-the Type: text / Plain \ R & lt \ nConnection: Close " ) ;
mg_send (NC, Content, strlen (Content));
NC -> the flags | = MG_F_SEND_AND_CLOSE;
}
// send the file, the file location is relative to the path of s_http_server_opts.document_root
void the HttpService :: mgSendFile ( struct mg_connection NC *, struct * HM http_message, const char * filePath) {
mg_http_serve_file(nc, hm, filePath, mg_mk_str("text/plain"), mg_mk_str(""));
}
//初始化并启动
bool HttpService::start(const char *port) {
struct mg_mgr mgr;
struct mg_connection *nc;
mg_mgr_init(&mgr, NULL);
printf("Starting web server on port %s\n", port);
nc = mg_bind(&mgr, port, mgEvHandler);
if (nc == NULL) {
printf("Failed to create listener\n");
return false;
}
// Set up HTTP server parameters
mg_set_protocol_http_websocket(nc);
s_http_server_opts.document_root = "."; //文件相对路径 Serve current directory
s_http_server_opts.enable_directory_listing = "yes";
for (;;) {
mg_mgr_poll(&mgr, 1000); //1s轮训一次
}
mg_mgr_free(&mgr);
return true;
}
3.vs2019 project file to download: vs2019_HttpSvr.zip
the above.
Reproduced in: https: //www.cnblogs.com/chevin/p/11051867.html