如何用cpp-httplib高效构建查询的HTTP服务?
摘要:介绍了如何使用轻量级 C++ 库 cpp-httplib 快速构建支持文本、HTML 页面和 JSON 数据交互的 HTTP 服务器。
1. 引言
cpp-httplib 是一个用 C++11 编写的轻量级、跨平台的 HTTP/HTTPS 服务器和客户端库。它由 yhirose 开发并维护,项目托管在 GitHub 上。在 C/C++ 生态中,笔者不能说 cpp-httplib 是最好的,但一定是最易于使用的 HTTP 服务器组件——它是基于头文件的库,只需要引入 httplib.h 这个头文件能实现所有基于 http/https 协议的功能。
2. 实例
2.1 返回文本
首先写一个最简单的 Hello World :
#include <httplib.h>
using namespace std;
int main() {
httplib::Server svr;
svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
res.set_content("Hello World!", "text/plain");
});
svr.listen("0.0.0.0", 8080);
return 0;
}
这段代码的意思很简单,启动一个 HTTP 服务器,然后监听 URL 为 /hi 、端口号为8080 的 Get 请求,并且返回一个 Hello World! 的文本。运行这个程序之后,在浏览器中输入http://127.0.0.1:8080/hi,即可看到这个文本。
2.2 返回页面
返回文本的 Hello World 太简单了,服务器能传输多种 MIME 类型(MIME Type)的数据到浏览器端显示,例如返回一个 HTML 页面:
#include "HttpServer.h"
#include <httplib.h>
using namespace std;
int main() {
httplib::Server svr;
svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
std::string html = R"(
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello</title>
</head>
<body>
<h1>Hello World!</h1>
<p>这是由 cpp-httplib 提供的 HTML 页面。</p>
</body>
</html>
)";
res.set_content(html, "text/html");
});
std::cout << "Server listening on http://0.0.0.0:8080/hi\n";
svr.listen("0.0.0.0", 8080);
return 0;
}
2.3 返回JSON
在现代前后端分离的项目绝大多数都使用 JSON(JavaScript Object Notation)作为数据传输格式。这是当前 Web 开发的事实标准,RESTful API 也推荐使用 JSON 作为请求/响应体格式。
