Mongoose is a network library for C/C++. It implements event-driven non-blocking APIs for TCP, UDP, HTTP, WebSocket, MQTT.
mongoose很小巧,只有两个文件mongoose.h/cpp,拿来就可以用.
下载地址:
https://github.com/cesanta/mongoose
1.simplest http server
2.restful server
3.simplest https server
4.multi-thread server
1.simplest http server
Mongoose有两个基本的结构体:
-
struct mg_mgr 事件管理器,管理所有激活的连接
-
struct mg_connection 单个连接描述结构
下面的示例代码创建了一个web server,事件处理函数fn中实现了三个简单的能力,一个显示根目录文件列表、一个显示hello Mongoose的html页面、一个简单的post请求计算两个数之和。
1.1代码
static void fn(struct mg_connection* c, int ev, void* ev_data, void* fn_data)
{
//MG_EV_HTTP_MSG表示为http请求
if (ev == MG_EV_HTTP_MSG)
{
struct mg_http_message* hm = (struct mg_http_message*)ev_data;
//1.get请求示例,显示Hello Mongoose页面
if (mg_http_match_uri(hm, "/hello"))
{
mg_http_reply(c, 200, "", "<html><head><title>mongoose demo</title></head><body><h1>Hello Mongoose!</h1></body></html>\n");
}
//2.post请求示例,请求体json示例{"a":10,"b":20},计算a+b的值
else if (mg_http_match_uri(hm, "/api/sum"))
{
double a = 0;
double b = 0;
mg_json_get_num(hm->body, "$.a", &a);
mg_json_get_num(hm->body, "$.b", &b);
double sum = a + b;
mg_http_reply(c, 200, "Content-Type: application/json\r\n", "{\"result\":%lf}", sum);
}
//3.显示当前目录文件列表
else
{
struct mg_http_serve_opts opts = { 0 };
opts.root_dir = ".";
mg_http_serve_dir(c, hm, &opts);
}
}
}
void main()
{
//1.创建事件管理器
struct mg_mgr mgr;
//设置日志级别为DEBUG,如果不做设置,默认情况下运行程序控制台不打印任何请求响应消息
mg_log_set(MG_LL_DEBUG);
//2.初始化事件管理器
mg_mgr_init(&mgr);
//3.创建http监听
mg_http_listen(&mgr, "http://127.0.0.1:8080", fn, NULL);
//4.开启事件循环
for (;;)
{
// 1000ms为超时时长
mg_mgr_poll(&mgr, 1000);
}
mg_mgr_free(&mgr);
}
1.2测试
启动httpserver 程序
1.2.1 浏览器访问:http://127.0.0.1:8080:
将显示exe程序根目录文件列表
1.2.2 浏览器访问: http://127.0.0.1:8080/hello:
将显示Hello Mongoose
1.2.3 使用postman: 发送post请求:
http://127.0.0.1:8080/api/sum,
请求json参数为{"a": 100, "b": 2},