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服务器的实现思路与工作流程类似。
   
 
