Mongoose Web Server是一款易于使用的Web服务器,它可以嵌入到其它应用程序中,为其提供Web接口。
mongoose的代码着实轻量,先看看它的特点:
1. 在整个的实现是使用C语言编写
2. 整个代码也只有一个mongoose.c和mongoose.h两个文件, 从引入第三方的考虑上也着实不多。
3. 实现的功能还是非常多的,从使用的层面上来说功能还是比较全面。只不过不知道是否是为了第三方使用的方便还是怎么地,它的代码只用了两个源文件罢了。诸多的功能也大以宏的开始与结束来区分。
4. 示例非常齐全,所有的功能都有单独的示例。
5.支持夸平台。
git 仓库 https://github.com/cesanta/mongoose
下面是使用 mongoose 实现简单的封装。
HttpService .h 的实现:
#pragma once
/*
Http服务
*/
#ifdef _WIN32
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
#endif
#include "mongoose.h"
class HttpService {
public:
bool start(const char *port);
private:
static void mgEvHandler(struct mg_connection *nc, int ev, void *p);
static void mgSendBody(struct mg_connection *nc, const char *content); //发送body信息
static void mgSendFile(struct mg_connection *nc, struct http_message *hm, const char* filePath);
static struct mg_serve_http_opts s_http_server_opts;
};
HttpService .cpp 的实现:
#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);
memcpy(body, msg->body.p, msg->body.len);
//uri内容
char* uri = new char[msg->uri.len + 1];
memset(uri, 0, msg->uri.len + 1);
memcpy(uri, msg->uri.p, msg->uri.len);
//返回body信息
mgSendBody(nc, "body content");
//返回下载文件
//mgSendFile("相对于s_http_server_opts.document_root的文件路径");
delete uri;
delete body;
}
}
//发送body信息
void HttpService::mgSendBody(struct mg_connection *nc, const char *content) {
mg_send_head(nc, 200, strlen(content), "Content-Type: text/plain\r\nConnection: close");
mg_send(nc, content, strlen(content));
nc->flags |= MG_F_SEND_AND_CLOSE;
}
//发送文件,文件的位置是相对于s_http_server_opts.document_root的路径
void HttpService::mgSendFile(struct mg_connection *nc, struct http_message *hm, 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;
}