c++ http第一个服务

c++ http第一个服务

一、下载相关依赖:这是一个git开源项目 代码仓地址

二、演示代码,编译参数:g++ test.cpp -I/**** -lpthread

c++ 复制代码
#include <httplib.h>
using namespace httplib;

void wuhan(const Request &req, Response &res)
{
    printf("httplib server recv a req: %s\n ", req.path.c_str() );
    res.set_content("<html>  \
                        <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"> \
                        <h1> 武汉, 加油!</h1></html>",
                    "text/html");
    res.status = 200;
}

int main(void)
{
    using namespace httplib;

    Server svr;
    svr.set_base_dir("./");

/// Get
svr.Get("/wuhan", wuhan);


    svr.Get("/hi", [](const Request& req, Response& res) {
        res.set_content("Hello World!", "text/plain");
    });

    svr.Get(R"(/numbers/(\d+))", [&](const Request& req, Response& res) {
        auto numbers = req.matches[1];
        res.set_content(numbers, "text/plain");
    });

    svr.Get("/body-header-param", [](const Request& req, Response& res) {
        if (req.has_header("Content-Length")) {
            auto val = req.get_header_value("Content-Length");
        }
        if (req.has_param("key")) {
            auto val = req.get_param_value("key");
        }
        res.set_content(req.body, "text/plain");
    });

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

    /// listen
    svr.listen("localhost", 1234);
}

三、访问网址http://localhost:1234/hi

相关推荐
eqwaak07 分钟前
数据预处理与可视化流水线:Pandas Profiling + Altair 实战指南
开发语言·python·信息可视化·数据挖掘·数据分析·pandas
mit6.82413 分钟前
10.5 数位dp
c++·算法
初圣魔门首席弟子19 分钟前
C++ STL 向量(vector)学习笔记:从基础到实战
c++·笔记·学习
青草地溪水旁30 分钟前
Visual Studio Code中launch.json深度解析:C++调试的艺术
c++·vscode·json
m0_5522008235 分钟前
《UE5_C++多人TPS完整教程》学习笔记62 ——《P63 多人游戏中的开火特效(Fire Effects in Multiplayer)》
c++·游戏·ue5
共享家952740 分钟前
QT-常用控件(一)
开发语言·qt
Y学院43 分钟前
实战项目:鸿蒙多端协同智能家居控制 App 开发全流程
开发语言·鸿蒙
十碗饭吃不饱1 小时前
WebClient工具调用HTTP接口报错远程主机断开连接
网络·网络协议·http
liu****1 小时前
基于websocket的多用户网页五子棋(九)
服务器·网络·数据库·c++·websocket·网络协议·个人开发
liu****1 小时前
基于websocket的多用户网页五子棋(八)
服务器·前端·javascript·数据库·c++·websocket·个人开发