首页 > 其他分享 >httplib 库介绍与使用

httplib 库介绍与使用

时间:2023-07-14 12:13:24浏览次数:29  
标签:httplib const pattern 介绍 Server handler 使用 svr

说明: cpp-httplib 是个开源的库,是一个c++封装的http库,使用这个库可以在linux、windows平台下完成http客户端、http服务端的搭建,这是一个多线程“阻塞”HTTP 库。 使用起来非常方便,只需要包含头文件httplib.h即可。 源码库地址:https://github.com/yhirose/cpp-httplib   httplib 库基本结构: 发送请求Request类的组成:   class Request { std::string method;  // 请求方法 std::string path; // 请求路径 map<std::string, std::string> param;  // 查询字符串(查询字符串中) map<std::string, std::string> headers;// 键值对头部 std::string body; //正文 };     响应数据类Response的组成:   class Response { int status; //返回的状态码 map<std::string,std::string> headers; //返回的价值对头部 std::string body; //正文 };     服务端Server 类的组成:   class Server { public:   using Handler = std::function<void(const Request &, Response &)>;   using HandlerWithContentReader = std::function<void(       const Request &, Response &, const ContentReader &content_reader)>;   using Expect100ContinueHandler =       std::function<int(const Request &, Response &)>;     Server();     virtual ~Server();     virtual bool is_valid() const;     Server &Get(const char *pattern, Handler handler);   Server &Post(const char *pattern, Handler handler);   Server &Post(const char *pattern, HandlerWithContentReader handler);   Server &Put(const char *pattern, Handler handler);   Server &Put(const char *pattern, HandlerWithContentReader handler);   Server &Patch(const char *pattern, Handler handler);   Server &Patch(const char *pattern, HandlerWithContentReader handler);   Server &Delete(const char *pattern, Handler handler);   Server &Delete(const char *pattern, HandlerWithContentReader handler);   Server &Options(const char *pattern, Handler handler);     客户端Client 类的组成:   class Client { //创建client Client(host,port); Get() Post() Put() ... };   简单实例: Server:   #define CPPHTTPLIB_OPENSSL_SUPPORT #include "path/to/httplib.h" // HTTP httplib::Server svr; // HTTPS httplib::SSLServer svr; svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {   res.set_content("Hello World!", "text/plain"); }); svr.listen("0.0.0.0", 8080);   Client:   #define CPPHTTPLIB_OPENSSL_SUPPORT #include "path/to/httplib.h" // HTTP httplib::Client cli("http://cpp-httplib-server.yhirose.repl.co"); // HTTPS httplib::Client cli("https://cpp-httplib-server.yhirose.repl.co"); auto res = cli.Get("/hi"); res->status; res->body;   SSL Support:   SSL support 要用到 CPPHTTPLIB_OPENSSL_SUPPORT. libssl and libcrypto 的支持。 现在只有 httplib 1.1.1 支持ssl 服务器。   #define CPPHTTPLIB_OPENSSL_SUPPORT #include "path/to/httplib.h" // Server httplib::SSLServer svr("./cert.pem", "./key.pem"); // Client httplib::Client cli("https://localhost:1234"); // scheme + host httplib::SSLClient cli("localhost:1234"); // host // Use your CA bundle cli.set_ca_cert_path("./ca-bundle.crt"); // Disable cert verification cli.enable_server_certificate_verification(false);   g++ -o service service.cpp -I/usr/local/openssl/include -L/usr/local/openssl/lib -lssl -lcrypto -pthread   完整简单web例子: #include <stdio.h> #include <iostream>   #include <jsoncpp/json/json.h> #include "httplib.h"   using namespace httplib; using namespace std;   int g_val = 100; void Get_CallBackFunc(const Request& req, Response& resp) {     printf("%d\n", g_val);     cout << req.method << endl;      printf("i am Get_CallBackFunc\n");       const char* lp = "<html><h2>hello bite!</h2></html>";     resp.set_content(lp, strlen(lp), "text/html"); }   int main() {     Server http_svr;     int a = 10;     http_svr.Get("/abc", Get_CallBackFunc);     http_svr.Post("/login", [](const Request& req, Response& resp){             cout << req.body << endl;               Json::Value resp_json;             resp_json["login_status"] = true;             Json::FastWriter w;             resp.body = w.write(resp_json);               resp.set_header("Content-Type", "application/json");             });     http_svr.set_mount_point("/", "./web");     http_svr.listen("0.0.0.0", 21010);     return 0; }     完整简单upload例子: #include "httplib.h" #include <iostream> #include <fstream>   using namespace httplib; using namespace std;   int main(void) {     Server svr;     svr.Post("/post", [](const Request &req, Response &res) {         auto music_file = req.get_file_value("music_file");           cout << "image file length: " << music_file.content.length() << endl              << "image file name: " << music_file.filename << endl;         {             ofstream ofs(music_file.filename, ios::binary);             ofs << music_file.content;         }         res.set_content("done", "text/plain");     });     svr.set_mount_point("/", "./www");     /// listen     svr.listen("0.0.0.0", 9089); }  

标签:httplib,const,pattern,介绍,Server,handler,使用,svr
From: https://www.cnblogs.com/kn-zheng/p/17553355.html

相关文章

  • java:不再支持源选项 5。请使用 6 或更高版本。
    <properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.encoding>UTF-8</maven.compiler.encoding><java.version>10</java.version><maven.co......
  • vue 使用document.execCommand失效
    document.execCommand当一个HTML文档切换到设计模式时,document暴露 execCommand 方法,该方法允许运行命令来操纵可编辑内容区域的元素。大多数命令影响document的 selection(粗体,斜体等),当其他命令插入新元素(添加链接)或影响整行(缩进)。当使用contentEditable时,调用 execComman......
  • nodejs中jwt的使用
    前言在浏览器和服务端的交互中,http请求是无状态的,那在web项目中准确无误的保存用户的登录状态是前后端交互中必须要解决的问题。目前在web端解决登录认证的问题分为三种base64session/cookietoken下面介绍下token中jwt实现登录验证的方式。基本概念了解下几种不同的认证方式base......
  • 记录下Jenkins的使用
    前言文章主要记录下自己搭建前端CI/CD的整个流程。环境搭建一台安装了centos7.x系统的主机安装Java环境//安装>sudoyuminstalljava//测试是否安装成功>java-version安装wget>sudoyuminstallwget安装jenkins//设置镜像源>sudowget-O/etc/yum.repos.d/jenkins......
  • Nginx之数据流代理stream模块简介和使用 ---九五小庞
    一、stream模块简介  stream模块一般用于TCP/UDP数据流的代理和负载均衡,通过stream模块我们可以代理转发tcp报文。ngx_stream_core_module模块从1.9.0版开始提供。默认情况下,此模块不是构建的,应该使用–withstream配置参数启用它,即我们需要使用./configure--with-stream的方......
  • 使用Debian 11基础镜像制作java8镜像
    下面是dockerfile内容:FROMdebian:bullseye#切换apt源为清华源,并安装vimpingtelnet命令RUNapt-getupdate&&aptinstall-yapt-transport-httpsca-certificates&&\cp/etc/apt/sources.list/etc/apt/sources.list.bak&&\echo"debhttps:......
  • markdown的使用说明
    markdown的使用说明摘自B站Up维素s一、标题语法:#(一级标题)##(二级标题)###(三级标题)......代码:#这是一级标题##这是二级标题效果:这是一级标题这是二级标题快捷键:Ctrl+数字1~6可以快速将选中的文本调成对应级别的标题Ctrl+0可以快速将选中的文......
  • postgresql 简单使用
    编译安装的启动数据库:/usr/local/postgresql/bin/pg_ctl-D/data/postgresql-llogfilestart停止数据库:/usr/local/postgresql/bin/pg_ctl-D/data/postgresqlstop-mfast登录数据库:/usr/local/postgresql/bin/psqlpostgres 配置文件:/data/postgresql/postgresql.con......
  • 使用Certbot免费https证书运行django
    CertbotインストールbashsudoaptinstallcertbotNginxを停止bashsudosystemctlstopnginx......
  • 使用Patroni管理LightDB高可用
    使用Patroni管理LightDB高可用测试环境CPU:海光x86OS:KylinAdvancedServerV10SP1LightDB:13.8-22.3Patroni:2.1.3etcd:3.5.4安装部署etcd集群需要3台机器。centos/RHEL等可以从epel获取etcd。麒麟ky10,ky10sp1没有etcd包,可以使用lightdb预编译的etcd-3.5.4。......