相信大家都有实现http服务器的需求,可能只是实现基本接口,不需要大而全,这里有一个特别好的实现,麻雀虽小却五脏俱全。
纯头文件的实现,支持windows和Linux,使用极其方便,直接include一个头文件即可。
即有服务端,又有客户端,用c++11编写。
可以支持SSL,还可以支持ZIP压缩。真的是不可多得的好东西。
项目地址见: https://github.com/yhirose/cpp-httplib ,作者一直在维护,新加了很多功能特性。
server示例
R"(/numbers/(\d+))" 是/numbers/1 , /numbers/2 等等。。通配地址
#include <httplib.h>
int main(void)
{
using namespace httplib;
Server svr;
svr.Get("/hi", [](const Request& req, Response& res) {
res.set_content("Hello World!", "text/plain");
});
svr.Get(R"(/numbers/(\d+))", [&](const Request& req, Response& res) {
auto numbers = req.matches[1];
res.set_content(numbers, "text/plain");
});
svr.Get("/stop", [&](const Request& req, Response& res) {
svr.stop();
});
svr.listen("localhost", 1234);
}
client示例
httplib::Client cli("yahoo.com");
auto res = cli.Get("/");
res->status; // 301
cli.follow_location(true);
res = cli.Get("/");
res->status; // 200