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

相关推荐
czt_java4 分钟前
线程安全问题
java·开发语言·jvm
techdashen9 分钟前
Rust 模块和文件不是一回事:一次讲清 `mod`、`use`、`pub use`
开发语言·后端·rust
Wy_编程12 分钟前
go中的协程Goroutine
开发语言·golang
lzh2004091921 分钟前
手撕线程池:巩固Linux线程知识
linux·c++
basketball61627 分钟前
C++ 命名空间知识点总结:从入门到合理设计
开发语言·c++
WL_Aurora29 分钟前
Java多线程详解(一)
java·开发语言
RSTJ_162543 分钟前
PYTHON+AI LLM DAY FOURTY-EIGHT
开发语言·人工智能·python·深度学习
南宫萧幕43 分钟前
HEV能量管理建模实战:从零搭建 Simulink 物理环境到 Python(DQN) 强化学习联合仿真调通
开发语言·python·算法·matlab·汽车·控制
lsx2024061 小时前
C++ 接口(抽象类)
开发语言
handler011 小时前
【C++ 算法竞赛基础】数论篇:核心公式、经典例题与高频模板
开发语言·c++·算法·蓝桥杯·数论·最大公约数·最小公倍数