1 Star 0 Fork 0

netwan / webcc

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
LGPL-3.0

Webcc - C++ HTTP 程序库

注意:master 分支的代码,避免了对 Boost 的依赖,但是需要 C++17 编译器;Asio 用的是独立版,并不是随 Boost 发布的 Asio。vs2013_compatible 分支则保留了对 Boost 的依赖,但是能在 VS2013 中编译。

基于 Asio 开发的轻量级 C++ HTTP 程序库,同时支持客户端与服务端。

不管你是要访问 HTTP 服务(比如调用 REST API、下载一个文件),还是要在你的程序里嵌入一个 HTTP 服务(比如 REST Server),Webcc 都是个不错的选择。

Boost Beast 没有一个开箱即用的 HTTP Server,微软 cpprest 的 API 设计复杂,且 server 部分也几乎不可用。Webcc 能满足大多数需求,又兼顾了性能和代码质量。这一点你看一下我们的代码心里就有数了。

编译指南,目前只有英文版。

代码仓库: https://github.com/sprinfall/webcc。 请认准链接,其他人 fork 的仓库,都不是最新的。

功能概述

  • 跨平台: Windows,Linux 及 MacOS
  • 简单好用的客户端 API,借鉴了 Python 的 requests 程序库
  • 支持 SSL/HTTPS,依赖 OpenSSL(可选)
  • 支持 GZip 压缩,依赖 Zlib(可选)
  • 持久连接 (Keep-Alive)
  • 数据串流 (Streaming)
    • 客户端:可以上传、下载大型文件
    • 服务端:可以伺服、接收大型文件
  • 支持 Basic & Token 认证/授权
  • 超时控制(目前仅客户端)
  • 代码遵守 Google C++ Style
  • 自动化测试和单元测试保证质量
  • 无内存泄漏(VLD 检测)

客户端 API

先来看一个完整的例子:

#include <iostream>

#include "webcc/client_session.h"
#include "webcc/logger.h"

int main() {
  // 首先配置日志输出(到控制台/命令行)
  WEBCC_LOG_INIT("", webcc::LOG_CONSOLE);
  
  // 创建会话
  webcc::ClientSession session;

  try {
    // 发起一个 HTTP GET 请求
    auto r = session.Send(webcc::RequestBuilder{}.
                          Get("http://httpbin.org/get")
                          ());

    // 输出响应数据
    std::cout << r->data() << std::endl;

  } catch (const webcc::Error& error) {
    // 异常处理
    std::cerr << error << std::endl;
  }

  return 0;
}

如你所见,这里通过一个辅助类 RequestBuilder,串联起各种参数,最后再生成一个请求对象。注意不要漏了最后的 () 操作符。

通过 Query() 可以方便地指定 URL 查询参数:

session.Send(webcc::RequestBuilder{}.
             Get("http://httpbin.org/get").
             Query("key1", "value1").Query("key2", "value2")
             ());

要添加额外的头部也很简单:

session.Send(webcc::RequestBuilder{}.
             Get("http://httpbin.org/get").
             Header("Accept", "application/json")
             ());

访问 HTTPS 和访问 HTTP 没有差别,对用户是透明的:

session.Send(webcc::RequestBuilder{}.Get("https://httpbin.org/get")());

注意:对 HTTPS/SSL 的支持,需要启用编译选项 WEBCC_ENABLE_SSL,也会依赖 OpenSSL。

列出 GitHub 公开事件 (public events) 也不是什么难题:

auto r = session.Send(webcc::RequestBuilder{}.
                      Get("https://api.github.com/events")
                      ());

然后,你可以把 r->data() 解析成 JSON 对象,随便用个什么 JSON 程序库。

我在示例程序里用的是 jsoncpp,但是 Webcc 本身并不理解 JSON,用什么 JSON 程序库,完全是你自己的选择。

RequestBuilder 本质上是为了解决 C++ 没有“键值参数”的问题,它提供了很多函数供你定制请求的样子。

为了列出一个授权的 (authorized) GitHub 用户的“粉丝” (followers),要么使用 Basic 认证

session.Send(webcc::RequestBuilder{}.
             Get("https://api.github.com/user/followers").
             AuthBasic(login, password)  // 应该替换成具体的账号、密码
             ());

要么使用 Token 认证

session.Send(webcc::RequestBuilder{}.
             Get("https://api.github.com/user/followers").
             AuthToken(token)  // 应该替换成具体合法的 token
             ());

尽管 持久连接 (Keep-Alive) 这个功能不错,你也可以手动关掉它:

auto r = session.Send(webcc::RequestBuilder{}.
                      Get("http://httpbin.org/get").
                      KeepAlive(false)  // 不要 Keep-Alive
                      ());

其他 HTTP 请求的 API 跟 GET 并无太多差别。

POST 请求需要一个“体” (body),就 REST API 来说通常是一个 JSON 字符串。让我们 POST 一个 UTF-8 编码的 JSON 字符串:

session.Send(webcc::RequestBuilder{}.
             Post("http://httpbin.org/post").
             Body("{'name'='Adam', 'age'=20}").Json().Utf8()
             ());

Webcc 可以把大型的响应数据串流到临时文件,串流在下载文件时特别有用。

auto r = session.Send(webcc::RequestBuilder{}.
                      Get("http://httpbin.org/image/jpeg")
                      (), true);  // stream = true

// 把串流的文件移到目标位置
r->file_body()->Move("./wolf.jpeg");

不光下载,上传也可以串流:

auto r = session.Send(webcc::RequestBuilder{}.
                      Post("http://httpbin.org/post").
                      File(path)  // 应该替换成具体的文件路径
                      ());

这个文件在 POST 时,不会一次加载到内存,而是读一块数据发一块数据,直到发送完。

注意,Content-Length 头部还是会设置为文件的真实大小,不同于 Transfer-Encoding: chunked 的分块数据形式。

更多示例和用法,请参考 examples 目录。

服务端 API

Hello, World!

下面是个 Hello, World! 级别的服务程序。 程序运行后,打开浏览器,输入 http://localhost:8080,页面显示 Hello, World!

class HelloView : public webcc::View {
public:
  webcc::ResponsePtr Handle(webcc::RequestPtr request) override {
    if (request->method() == "GET") {
      return webcc::ResponseBuilder{}.OK().Body("Hello, World!")();
    }

    return {};
  }
};

int main() {
  try {
    webcc::Server server(8080);

    server.Route("/", std::make_shared<HelloView>());

    server.Run();

  } catch (const std::exception&) {
    return 1;
  }

  return 0;
}

简单解释一下。一个服务器 (server) 对应多个视图 (view),不同的视图对应不同的资源,视图通过 URL 路由,且 URL 可以为正则表达式。

完整代码请见 examples/hello_world_server

下面看一个更复杂的例子。

Book Server

假定你想创建一个关于书的服务,提供下面这些 REST API:

  • 查询书
  • 添加一本新书
  • 获取一本书的详情
  • 更新一本书的信息
  • 删除一本书

这是一组典型的 CRUD 操作。

前两个操作通过 BookListView 实现:

ListView,DetailView 的命名方式,参考了 Django REST Framework。ListView 针对一列资源,DetailView 针对单个资源。

class BookListView : public webcc::View {
public:
  webcc::ResponsePtr Handle(webcc::RequestPtr request) override {
    if (request->method() == "GET") {
      return Get(request);
    }
    if (request->method() == "POST") {
      return Post(request);
    }
    return {};
  }
  
private:
  // 查询书
  webcc::ResponsePtr Get(webcc::RequestPtr request);

  // 添加一本新书
  webcc::ResponsePtr Post(webcc::RequestPtr request);
};

其他操作通过 BookDetailView 实现:

class BookDetailView : public webcc::View {
public:
  webcc::ResponsePtr Handle(webcc::RequestPtr request) override {
    if (request->method() == "GET") {
      return Get(request);
    }
    if (request->method() == "PUT") {
      return Put(request);
    }
    if (request->method() == "DELETE") {
      return Delete(request);
    }
    return {};
  }
  
protected:
  // 获取一本书的详情
  webcc::ResponsePtr Get(webcc::RequestPtr request);

  // 更新一本书的信息
  webcc::ResponsePtr Put(webcc::RequestPtr request);

  // 删除一本书
  webcc::ResponsePtr Delete(webcc::RequestPtr request);
};

我们挑一个函数出来看一下吧:

webcc::ResponsePtr BookDetailView::Get(webcc::RequestPtr request) {
  if (request->args().size() != 1) {
    // NotFound (404) 意味着 URL 所指定的资源没有找到。
    // 这里用 BadRequest (400) 应该也是合理的。
    // 不过,后面可以看到,这个视图匹配了 "/books/(\\d+)" 这个 URL,参数肯定不会有问题的。
    // 所以这里的错误处理,只是出于防范,和编程的严谨。
    // Webcc 没有对 URL 参数做强类型的处理,那么代码写起来太复杂了。
    return webcc::ResponseBuilder{}.NotFound()();
  }

  const std::string& book_id = request->args()[0];

  // 通过 ID 找到这本书,比如,从数据库里。
  // ...

  if (<没找到>) {
    return webcc::ResponseBuilder{}.NotFound()();
  }

  // 把这本书转换成 JSON 字符串,并设为响应数据。
  return webcc::ResponseBuilder{}.OK().Data(<JsonStringOfTheBook>).
      Json().Utf8()();
}

最后一步,把 URLs 路由到特定的视图,然后开始运行:

int main(int argc, char* argv[]) {
  // ...

  try {
    webcc::Server server(8080);

    server.Route("/books",
                 std::make_shared<BookListView>(),
                 { "GET", "POST" });

    // ID 通过正则表达式匹配出来
    server.Route(webcc::R("/books/(\\d+)"),
                 std::make_shared<BookDetailView>(),
                 { "GET", "PUT", "DELETE" });

    // 开始运行(注意:阻塞调用)
    server.Run();

  } catch (const std::exception& e) {
    std::cerr << e.what() << std::endl;
    return 1;
  }

  return 0;
}

完整实现请见 examples/book_server

GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.

简介

暂无描述 展开 收起
LGPL-3.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/netwan/webcc.git
git@gitee.com:netwan/webcc.git
netwan
webcc
webcc
master

搜索帮助