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

相关推荐
陈旭金-小金子35 分钟前
发现 Kotlin MultiPlatform 的一点小变化
android·开发语言·kotlin
呃m37 分钟前
双重特征c++
c++
Mikhail_G39 分钟前
Python应用八股文
大数据·运维·开发语言·python·数据分析
景彡先生1 小时前
C++ 中文件 IO 操作详解
开发语言·c++
你怎么知道我是队长1 小时前
GO语言---defer关键字
开发语言·后端·golang
无影无踪的青蛙2 小时前
[C++] STL大家族之<map>(字典)容器(附洛谷)
开发语言·c++
二进制人工智能2 小时前
【OpenGL学习】(四)统一着色和插值着色
c++·opengl
a4576368762 小时前
Objective-c protocol 练习
开发语言·macos·objective-c
fajianchen2 小时前
Spring中观察者模式的应用
java·开发语言
追风赶月、2 小时前
【QT】控件一(QWidget、Button、Label)
开发语言·qt