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

相关推荐
传奇开心果编程1 小时前
【Rust入门知识点学与练】第24课:Trait 基础
开发语言·学习·rust
wuminyu4 小时前
Kafka中sendfile与mmap实现机制解析
java·linux·c语言·jvm·c++
言乐66 小时前
Python加速器4跨境网络加速器
运维·服务器·开发语言·网络·python
金金计较.7 小时前
Go语言-3
java·开发语言·golang
张小凡vip8 小时前
python--爬虫--经验积累的遇到的坑
开发语言·爬虫·python
Wang's Blog8 小时前
Java框架快速入门: Spring Security+OAuth2之云服务集成与多因子认证设计
java·开发语言·spring
门思科技8 小时前
LoRaWAN 网络容量估算:一个 SX1302 网关到底能带多少设备
开发语言·网络·php
大草原的小灰灰9 小时前
Python基础语法
开发语言·python
无小道9 小时前
C++——列表初始化
c++·列表初始化
blueSatchel9 小时前
c++action 编写(ros-humble)
c++·ros2