具體過(guò)程就不說(shuō)了,mongoose很小巧,只有兩個(gè)文件mongoose.h/cpp,拿來(lái)就可以用,并且官方文檔包括example也相當(dāng)?shù)呢S富,可以去官網(wǎng)或者GitHub上瀏覽下載,摘幾個(gè)相關(guān)的:
A. simplest http server
B. RESTful server
C. simplest https server
D. multi-thread server
實(shí)際上mongoose的注釋也很貼心了,文檔或demo中沒(méi)有提及到去mongoose.h里面仔細(xì)找找基本都能解決,說(shuō)幾個(gè)自用時(shí)的一點(diǎn)注意事項(xiàng):
- 關(guān)于結(jié)構(gòu)體
mg_serve_http_opts
,它是demo中常用在事件處理回調(diào)函數(shù)中的
void mg_serve_http(struct mg_connection *nc, struct http_message *hm, struct mg_serve_http_opts opts);
函數(shù)主要參數(shù),決定了server如何回應(yīng)client請(qǐng)求,包括回復(fù)內(nèi)容、顯示格式、權(quán)限控制等等許多選項(xiàng),如果有需要可以仔細(xì)閱讀該結(jié)構(gòu)體相關(guān)代碼與注釋;
- 在做RESTful server API的時(shí)候,難免要根據(jù)請(qǐng)求來(lái)訂制響應(yīng)方式,這里應(yīng)該注意mongoose提供的
mg_*_send_*
和mg_*_printf_*
系列函數(shù),根據(jù)實(shí)際需要來(lái)酌情選擇:
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的時(shí)候,需要用到SSL相關(guān)功能,首先要在mongoose.h頭文件開(kāi)始加上相關(guān)宏定義啟用SSL支持,配置好OpenSSL頭文件include路徑(我的在
D:\Code\openssl\inc32
,mongoose中的OpenSSL頭文件包含方式都是#include <openssl/...>
),并導(dǎo)入OpenSSL靜態(tài)庫(kù):
#define MG_ENABLE_SSL 1
#pragma comment(lib,"./openssl/libeay32.lib")
#pragma comment(lib,"./openssl/ssleay32.lib")
然后在調(diào)用
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);
創(chuàng)建mg_connection
對(duì)象的時(shí)候,通過(guò)mg_bind_opts
參數(shù)的成員ssl_cert
和ssl_key
分別導(dǎo)入服務(wù)器公鑰(證書(shū))和服務(wù)器私鑰。
至于如何獲取證書(shū),一般來(lái)說(shuō)在不必要第三方CA的web server常采用自簽名證書(shū)的方式,具體步驟可以參見(jiàn)上一篇博客:OpenSSL生成HTTPS自簽名證書(shū)