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

相关推荐
hd51cc5 分钟前
MFC 文档/视图 二
c++·mfc
wzfj1234518 分钟前
认识lambda
c++
老王熬夜敲代码31 分钟前
C++万能类:any
开发语言·c++·笔记
梦帮科技37 分钟前
第三十四篇:开源社区运营:GitHub Stars增长策略
开发语言·前端·爬虫·python·docker·架构·html
智者知已应修善业1 小时前
【数组删除重复数据灵活算法可修改保留重复数量】2024-3-4
c语言·c++·经验分享·笔记·算法
Cappi卡比1 小时前
【无标题】
c++
小成202303202651 小时前
Linux高级
linux·开发语言
m0_502724951 小时前
QT - 系统托盘
开发语言·qt
汉克老师1 小时前
GESP2025年12月认证C++五级真题与解析(编程题2 (相等序列))
c++·算法·贪心算法·中位数·质数分解
还不秃顶的计科生2 小时前
python循环中的enumerate用法
开发语言·python