Mongoose搭建RESTful http/https web server
具体过程就不说了,mongoose很小巧,只有两个文件mongoose.h/cpp,拿来即可以用,并且官方文档包括example也相当的丰富,可以去官网或者者GitHub上浏览下载,摘几个相关的:
A. simplest http server
B. RESTful server
C. simplest https server
D. multi-thread server
实际上mongoose的注释也很贴心了,文档或者demo中没有提及到去mongoose.h里面仔细找找基本都能处理,说几个自用时的一点注意事项:
- 关于结构体
mg_serve_http_opts,它是demo中常用在事件解决回调函数中的
void mg_serve_http(struct mg_connection *nc, struct http_message *hm, struct mg_serve_http_opts opts);函数主要参数,决定了server如何回应client请求,包括回复内容、显示格式、权限控制等等许多选项,假如有需要可以仔细阅读该结构体相关代码与注释;
- 在做RESTful server API的时候,难免要根据请求来订制响应方式,这里应该注意mongoose提供的
mg_*_send_*和mg_*_printf_*系列函数,根据实际需要来酌情选择:
void mg_send(struct mg_connection *, const void *buf, int len);int mg_printf(struct mg_connection *, const char *fmt, ...);void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...);void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len);void mg_send_response_line(struct mg_connection *nc, int status_code, const char *extra_headers);void mg_http_send_error(struct mg_connection *nc, int code, const char *reason);void mg_http_send_redirect(struct mg_connection *nc, int status_code, const struct mg_str location, const struct mg_str extra_headers);void mg_send_head(struct mg_connection *n, int status_code, int64_t content_length, const char *extra_headers);- 在搭建https server的时候,需要用到SSL相关功能,首先要在mongoose.h头文件开始加上相关宏定义启用SSL支持,配置好OpenSSL头文件include路径(我的在
D:\Code\openssl\inc32,mongoose中的OpenSSL头文件包含方式都是#include <openssl/...>),并导入OpenSSL静态库:
#define MG_ENABLE_SSL 1#pragma comment(lib,"./openssl/libeay32.lib")#pragma comment(lib,"./openssl/ssleay32.lib")而后在调用
struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address, MG_CB(mg_event_handler_t handler, void *user_data), struct mg_bind_opts opts);创立mg_connection对象的时候,通过mg_bind_opts参数的成员ssl_cert和ssl_key分别导入服务器公钥(证书)和服务器私钥。
至于如何获取证书,一般来说在不必要第三方CA的web server常采用自签名证书的方式,具体步骤可以参见上一篇博客:OpenSSL生成HTTPS自签名证书
说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Mongoose搭建RESTful http/https web server
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Mongoose搭建RESTful http/https web server