C++11 http服务端和客户端库cpp-httplib

C++11 http服务端和客户端库cpp-httplib

环境:

复制代码
http: yhirose/cpp-httplib v0.18.1
json: nlohmann/json v3.11.3

1. 简介

cpp-httplib 是一个轻量级且易于使用的 C++11 HTTP 库,由 yhirose 开发和维护,开源协议为MIT。它支持 HTTP/HTTPS 协议,可用于创建简单的客户端和服务器应用程序。

主要特性:

  • 支持 Windows、macOS 和 Linux等操作系统
  • 支持 HTTP/1.1 和 HTTPS 协议
  • 支持 GET、POST、PUT、DELETE 等 HTTP 方法
  • 支持文件上传和下载
  • 支持自定义响应头和请求头
  • 支持压缩和解压缩(如 gzip)
  • 支持路由功能,可以匹配和处理不同的 URL 路径

项目仓库地址:https://github.com/yhirose/cpp-httplib

2. http服务端代码

main.cpp

复制代码
#include "httplib.h"
#include "json.hpp"

#include <iostream>

using namespace httplib;
using json = nlohmann::json;

int main()
{
    Server httpServer;

    // /test
    httpServer.Get("/test",
                   [](const Request &req, Response &res)
                   {
                       json response = json::parse(R"({"code":0,"message":"success","data":[1,2,3]})");
                       res.set_content(response.dump(), "application/json");
                   });

    // /user/:username
    httpServer.Post("/user/:username",
                    [](const Request &req, Response &res)
                    {
                        auto username = req.path_params.at("username");

                        json response = {{"code", 0}, {"message", "success"}, {"data", {{"username", username}}}};
                        res.set_content(response.dump(), "application/json");
                    });

    // /exit
    httpServer.Get("/exit",
                   [&](const Request &req, Response &res)
                   {
                       httpServer.stop();
                   });

    std::cout << "http://0.0.0.0:8080" << std::endl;
    std::cout << "GET  /test" << std::endl;
    std::cout << "POST /user/:username" << std::endl;
    std::cout << "GET  /exit" << std::endl;
    httpServer.listen("0.0.0.0", 8080);

    return 0;
}

CMakeLists.txt

复制代码
cmake_minimum_required(VERSION 3.11)

project(main)

add_executable( ${PROJECT_NAME} main.cpp json.hpp httplib.h)
相关推荐
程序员老舅12 分钟前
C++参数传递:值、指针与引用的原理与实战
c++·c/c++·值传递·引用传递·指针传递·参数传递机制
liu****1 小时前
8.list的使用
数据结构·c++·算法·list
立志成为大牛的小牛1 小时前
数据结构——二十六、邻接表(王道408)
开发语言·数据结构·c++·学习·程序人生
问道飞鱼1 小时前
【HTTP知识】HTTP OPTIONS 预检请求深度解析与优化策略
网络·网络协议·http·option·预检
草莓熊Lotso2 小时前
C++ 方向 Web 自动化测试入门指南:从概念到 Selenium 实战
前端·c++·python·selenium
CoderCodingNo3 小时前
【GESP】C++五级考试大纲知识点梳理, (5) 算法复杂度估算(多项式、对数)
开发语言·c++·算法
星河队长3 小时前
VS创建C++动态库和C#访问过程
java·c++·c#
沐怡旸4 小时前
【穿越Effective C++】条款02:尽量以const, enum, inline替换#define
c++·面试
tan180°4 小时前
Linux网络HTTP(中)(8)
linux·网络·http
给大佬递杯卡布奇诺5 小时前
FFmpeg 基本API avcodec_alloc_context3函数内部调用流程分析
c++·ffmpeg·音视频