具體過程就不說了,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自簽名證書