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

相关推荐
Zane19941224 分钟前
CAS 与原子类:Java 如何实现无锁编程
java·开发语言
码农颜1 小时前
6.3 主函数流程剖析
开发语言·php
TheBestRucy2 小时前
Python 九阳神功:从零筑基到线程飞升
服务器·开发语言·网络·人工智能·python
研☆香2 小时前
聊一聊前端的常见字 关键字
开发语言·前端·javascript
小小龙学IT2 小时前
FlatBuffers 深度解析:Google 开源零拷贝序列化库完全指南
c++·开源
wuminyu2 小时前
JDK21中虚拟线程和FFM协同实现高并发源码剖析
java·linux·c语言·jvm·c++
草莓橙子碗2 小时前
Claude 使用指南
开发语言·python
SWAGGY..2 小时前
【C++进阶】:(1)继承机制详解
java·jvm·c++
longxiaozhang63 小时前
C# Array类:数组其实没那么难
开发语言·c#
听取WA声一片(无恶意)3 小时前
CSP-J/CSP-S 深度优先搜索(DFS)完全讲义
c++·算法·深度优先