A C++11 single-file header-only cross platform HTTP/HTTPS library.
It’s extremely easy to setup. Just include the httplib.h file in your code!
NOTE:
This is a multi-threaded ‘blocking’ HTTP library. If you are looking for a ‘non-blocking’ library, this is not the one that you want.
cpp-httplib簡介
cpp-httplib
是一個以C++11特性編寫的,跨平台HTTP/HTTPS庫。使用時,隻需在代碼中包含
httplib.h
檔案。
注意:這是一個多線程的阻塞HTTP庫。
在簡易點餐系統的項目中,我使用httplib庫來實作http伺服器的搭建,是以我們在這裡介紹一下httplib的工作流程。
下載下傳位址:GitHub/yhirose/cpp-httplib
httplib.h頭檔案的組成
類 | 類名 |
---|---|
class Server | 服務端類 |
class Client | 用戶端類 |
struct Response | 響應資料類 |
struct Request | 請求資料類 |
class ThreadPool | 線程池類 |
服務端類的組成
class Server
{
…………
//get post put delete 方法
Server &Get(const char *pattern, Handler handler);
Server &Post(const char *pattern, Handler handler);
Server &Put(const char *pattern, Handler handler);
Server &Delete(const char *pattern, Handler handler);
…………
//監聽
bool listen(const char *host, int port, int socket_flags = 0);
};
Server類中,還包含了
map<pair<string,string>,function> route
這樣的請求與處理的路由表。
用戶端類的組成
class Client
{
………………
//建立client
explicit Client(const std::string &host, int port);
//post get head put delte 方法
Result Get(const char *path);
Result Head(const char *path);
Result Post(const char *path);
Result Put(const char *path);
Result Delete(const char *path);
………………
};
響應資料類的組成
struct Response
{
…………
int status = -1;//狀态碼
Headers headers;//頭部
std::string body;//正文
…………
};
請求資料類的組成
struct Request
{
…………
std::string method;//請求方法
std::string path;//請求路徑
std::string body;//正文
Match matches;//捕捉到的資料
…………
};
httplib的工作流程
文字描述
一、執行個體化一個Server對象,Server對象中有一個請求與處理路由表,記錄各種請求對應的處理函數。
二、注冊請求路由,告訴httplib,哪個請求應該用哪個函數處理。
三、搭建伺服器,開始監聽。
四、當伺服器收到一個用戶端連接配接,将建立連接配接抛入線程池,線程池中的線程負責與指定用戶端通信。
線程中的操作:
- 接收請求資料,按照http請求協定格式進行解析,執行個體化httplib:response對象,将解析資訊填入其中
-
根據請求資訊,在route路由表中查找對于這個請求有沒有對應的處理函數
(一)如果沒有,直接傳回404
(二)如果有,則使用對應的函數指針執行處理函數
處理函數:
(1)傳入請求資訊httplib:request
(2)執行個體化一個httplib:response對象傳入處理函數,在處理函數内部,使用者實作針對請求的業務處理,在業務處理完畢後填充response對象
-
線上程中執行完處理函數後,得到一個填充完的response對象
根據其中的資料組織http響應,回複給用戶端
- 等待還有沒有請求需要處理,沒有關閉套接字
圖檔描述

注:使用httplib搭建一個HTTP伺服器的實作思路與工作流程類似。