现在使用中的:cgicc + FastCGI
- CGI 和 FastCGI 在本质上都是一种协议,其中 FastCGI 是 CGI 的升级版本,在设计上可以更快地处理请求
- cgicc 是实现了这一协议的一个 C++ 库,在 rk 提供的示例代码里面就使用了 cgicc,它承担了解析 HttpRequest 和 返回 HttpResponse 的职责,但是实现方式的代码非常的原始
- Http 请求通过 nginx 代理给 FastCGI(由 FCGIWrap实现) 调用 cgi_server.cgi 脚本来实现对外的 Http 服务
- cgicc 项目地址:https://www.gnu.org/software/cgicc/
优化方向:
- 不再是 if-else 的方式来解析路径判断请求,而是有一套规范且优雅的请求接口
- 可以有全局的异常处理
最后回答的问题:
- 是否用 CGI
- 不用 CGI 的话可以选择什么库
- 选取标准:
- 是否易于编程,除了后续的实际代码撰写,还包括初期的依赖环境构建,毕竟要通过交叉编译
- CGI 和 其他的性能比较,以及各实现库之间的性能比较
CGI 路径:
- 在 Github 和 Gitee 上搜索 “cgi”、“cgicc” 都没有得到可以参考的范例
- 关于 C++ 的 AOP,C++ 因为没有 Java 这样子的反射,所以本身语言特性其实不支持 AOP,另类方式实现 C++ 的 AOP 来达到全局异常处理,暂时没有找到特别成熟的第三方库,大多是一些 coder 的学习实践:
- https://www.geek-share.com/detail/2665560080.html
- https://blog.csdn.net/wangdamingll/article/details/104803599
- https://www.cnblogs.com/qicosmos/p/4772389.html
网络库概念:
- 也就是真正做到高效网络服务的那些底层逻辑:怎么读字节流,用什么方式处理请求
- 主要有 asio、libevent、libuv
- 我们不会直接选择这些网络库,因为它们并不易于编程,我们要找的通常是基于这些库实现的一些 Http 请求的解析框架,当然有些也是直接自己实现网络库的,比如说 Facebook 的 proxygen
cpp-netlib
- 项目地址,看上去很专业:https://cpp-netlib.org/index.html
- C++ standard (currently C++11)
- 有一些并发工具,但这并不是我们的需求
- 放弃理由:源码地址实际 star 数只有 1.8k ,已经很久没有更新了,https://github.com/cpp-netlib/cpp-netlib
Facebook 的 proxygen
- 源码地址:https://github.com/facebook/proxygen
- 大厂背书,也是一个底层库,star 数 7.2k,8000+ commits
- 放弃理由:不够轻量级,You will need at least 3 GiB of memory to compile proxygen and its dependencies
cesanta 家的 mongoose
- star 数 7.3k,更新也很频繁,源码地址:https://github.com/cesanta/mongoose
- 强调了是 Embedded Web Server 和 安全性
- You will need at least 3 GiB of memory to compile proxygen and its dependencies
- 98.7% C 语言
- 具备完善的文档
- 因为没有像 httplib 那样很简洁的监听接口的写法,所以还是需要一些参考来怎么实现接口的:
- https://github.com/tashaxing/CppHttpDemo/blob/master/httpserver/http_server.cpp
- 这个看上去很合适(Api controller to manage GET, POST, PUT and DELETE methods.)https://github.com/FragJage/MongooseCpp
drogon
- star 数 5.8k,源码地址:https://github.com/an-tao/drogon
- Drogon is a C++14/17-based HTTP application framework
- Support JSON format request and response, very friendly to the Restful API application development
- Support ARM Architecture,很多文档里其实都没提这点,并不确定这点到底重不重要
- Provide a convenient lightweight ORM implementation that supports for regular object-to-database bidirectional mapping
- 具备完善的文档
- 接口编写代码示例:
app().registerHandler("/test?username={name}",
[](const HttpRequestPtr& req,
std::function<void (const HttpResponsePtr &)> &&callback,
const std::string &name)
{
Json::Value json;
json["result"]="ok";
json["message"]=std::string("hello,")+name;
auto resp=HttpResponse::newHttpJsonResponse(json);
callback(resp);
},
{
Get,"LoginFilter"});
#include <drogon/HttpController.h>
using namespace drogon;
n