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

相关推荐
xlq2232242 分钟前
22.多态(上)
开发语言·c++·算法
666HZ66643 分钟前
C语言——高精度加法
c语言·开发语言·算法
rainmanqqst1 小时前
C#Netcore支持Https
网络协议·http·https·c#
星释1 小时前
Rust 练习册 100:音乐音阶生成器
开发语言·后端·rust
D_evil__1 小时前
[C++高频精进] 并发编程:线程基础
c++
风生u2 小时前
go进阶语法
开发语言·后端·golang
666HZ6662 小时前
C语言——黑店
c语言·开发语言
Gomiko2 小时前
JavaScript基础(八):函数
开发语言·javascript·ecmascript
〝七夜5692 小时前
JVM内存结构
java·开发语言·jvm
初级炼丹师(爱说实话版)2 小时前
JAVA泛型作用域与静态方法泛型使用笔记
java·开发语言·笔记