25
Dec
2013
小型web服务器Mongoose试用
缘由
早先PC端有几个服务器由于需求牵扯到了一些HTTP请求,当时使用了Mongoose,当时没怎么接触,前段时间客户端做加速器又准备使用个小型web server,选定的也是这个,处于兴趣,前N个星期六抽了半天看了下相关文档,记录下(我承认我TM懒)。
简介
Mongoose是一个非常小巧的web服务器,支持C/C++、C#、Python、Ruby、Lua语言。它实现了对Socket的封装,提供了简洁的开发接口,性能也很好,主要用在嵌入式开发平台,主页是http://cesanta.com/
Mongoose可以编译成so,或者直接上源文件(就两个文件,适合携带),主要有以下特性:
- 可以运行在Windows,Mac,Unix/Linux,iPhone, Android和其他平台
- 脚本支持Lua,数据库支持SQLite,扩展性不错(PHP也能用)
- 支持CGI,SSL,SSI,Digest(MD5)认证,Websocket,WebDAV
- 支持断点续传,URL rewrite,文件黑名单,基于IP的ACL
- 干净简单的API,只有mongoose.h和mongoose.c
- 大量的实例
实例
在监听1125端口,如果请求的是hello.html
就返回这个网页,其他情况返回请求的目录,代码如下:
#include <iostream>
#include <string.h>
using namespace std;
#include "mongoose.h"
static int event_handle(struct mg_event* event)
{
if (event->type == MG_REQUEST_BEGIN)
{
if (strcmp(event->request_info->uri,"/hello.html") != 0)
{
char content[100];
// Prepare the message we're going to send
int content_length = snprintf(content, sizeof(content),
"Hello from mongoose! Requested: [%s] [%s]",
event->request_info->request_method, event->request_info->uri);
// Send HTTP reply to the client
mg_printf(event->conn,
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n" // Always set Content-Length
"\r\n"
"%s",
content_length, content);
// Returning non-zero tells mongoose that our function has replied to
return 1;
}
}
return 0;
}
int main()
{
const char* options[] = {
"listening_ports", "1125",
"document_root", "wwwroot",
NULL};
struct mg_context* ctx = mg_start(options,&event_handle,NULL);
if (ctx == NULL)
{
cout << "start failed\n";
}
else
{
cout << "start success\n";
}
getchar();
mg_stop(ctx);
return 0;
}
总结
总体来说Mongoose很让人惊喜,小巧强大,使用简便,还支持URL rewrite和正则表达式,并且可以通过Lua来扩展。下载的源码中有大部分的使用示例,官方文档也很齐全。
下载:http://cesanta.com/index.html#downloads
文档:http://cesanta.com/docs.html
上一篇: 设计模式 - 单例模式
上一篇: Argparse简易教程