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

相关推荐
SOC罗三炮6 分钟前
OpenHuman 源码深度解构:一个 Rust 驱动的本地优先 AI 个人助手
开发语言·人工智能·rust
心怀梦想的咸鱼10 分钟前
OpenCode 接入 API 报错 read ECONNRESET:基于环境变量的证书校验绕过方案
开发语言·php
酿情师10 分钟前
Microsoft Visual C++ Build Tools 2026 下载与安装指南(Windows)
c++·windows·microsoft
cany100027 分钟前
C++ -- 引用悬挂
c++
程序大视界40 分钟前
【Python系列课程】Python入门教程
开发语言·人工智能·python
morning_judger1 小时前
Agent系列(二)-记忆系统的设计
开发语言·python·机器学习
方也_arkling1 小时前
【Java-Day02】语法篇:变量/数据类型/标识符/运算符/类型转换
java·开发语言
RSTJ_16251 小时前
PYTHON+AI LLM DAY SIXTY-ONE
开发语言·python
zfoo-framework1 小时前
理解kotlin limitedParallelism(1)与Actor模型
android·开发语言·kotlin
.千余1 小时前
【C++】C++类与对象3:const成员函数与取地址运算符重载,权限管理的艺术
开发语言·c++