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)
相关推荐
Dream it possible!1 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
柠石榴1 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
王老师青少年编程1 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
澄澈天空3 小时前
C++ MFC添加RichEditControl控件后,程序启动失败
c++·mfc
Lzc7744 小时前
C++初阶——简单实现vector
c++·简单实现vector
一个小白14 小时前
C++——list模拟实现
开发语言·c++
程序员老舅5 小时前
C++ Qt项目教程:WebServer网络测试工具
c++·qt·测试工具·webserver·qt项目·qt项目实战
靡不有初1115 小时前
CCF-CSP第18次认证第一题——报数【两个与string相关的函数的使用】
c++·学习·ccfcsp
cookies_s_s6 小时前
Linux--进程(进程虚拟地址空间、页表、进程控制、实现简易shell)
linux·运维·服务器·数据结构·c++·算法·哈希算法
不想编程小谭7 小时前
力扣LeetCode: 2506 统计相似字符串对的数目
c++·算法·leetcode