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

相关推荐
小辉懂编程20 分钟前
C语言:51单片机实现数码管依次循环显示【1~F】课堂练习
c语言·开发语言·51单片机
醍醐三叶1 小时前
C++类与对象--2 对象的初始化和清理
开发语言·c++
Magnum Lehar2 小时前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
Mcworld8573 小时前
java集合
java·开发语言·windows
成功人chen某3 小时前
配置VScodePython环境Python was not found;
开发语言·python
wuqingshun3141593 小时前
蓝桥杯 16. 外卖店优先级
c++·算法·职场和发展·蓝桥杯·深度优先
purrrew3 小时前
【Java ee初阶】HTTP(2)
网络·网络协议·http
火星数据-Tina3 小时前
从HTTP轮询到WebSocket:如何让体育API性能提升100倍?
websocket·网络协议·http
海绵宝宝贾克斯儿3 小时前
C++中如何实现一个单例模式?
开发语言·c++·单例模式
史迪仔01124 小时前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式