Mongoose搭建RESTful http/https web server

具體過程就不說了,mongoose很小巧,只有兩個文件mongoose.h/cpp,拿來就可以用,并且官方文檔包括example也相當?shù)呢S富,可以去官網(wǎng)或者GitHub上瀏覽下載,摘幾個相關的:
A. simplest http server
B. RESTful server
C. simplest https server
D. multi-thread server


實際上mongoose的注釋也很貼心了,文檔或demo中沒有提及到去mongoose.h里面仔細找找基本都能解決,說幾個自用時的一點注意事項:

  • 關于結(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如何回應client請求,包括回復內(nèi)容、顯示格式、權限控制等等許多選項,如果有需要可以仔細閱讀該結(jié)構(gòu)體相關代碼與注釋;

  • 在做RESTful server API的時候,難免要根據(jù)請求來訂制響應方式,這里應該注意mongoose提供的mg_*_send_*mg_*_printf_*系列函數(shù),根據(jù)實際需要來酌情選擇:
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靜態(tài)庫:
#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對象的時候,通過mg_bind_opts參數(shù)的成員ssl_certssl_key分別導入服務器公鑰(證書)和服務器私鑰。
至于如何獲取證書,一般來說在不必要第三方CA的web server常采用自簽名證書的方式,具體步驟可以參見上一篇博客:OpenSSL生成HTTPS自簽名證書

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容