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

相关推荐
AA陈超1 分钟前
004 T02 - 俯视角摄像机系统 设计文档
网络·c++·ue5·虚幻引擎
-银雾鸢尾-8 分钟前
C#中的索引器
开发语言·c#
bu_shuo9 分钟前
c与cpp中的argc和argv
c语言·c++·算法
蓝创精英团队15 分钟前
VCPKG 跨平台C++ 库管理器
c++·vcpkg
Qlittleboy39 分钟前
PHP的接口参数传递的过多,max_input_vars = 5000
开发语言·php
Aurorar0rua39 分钟前
CS50 x 2024 Notes Algorithms - 02
c语言·开发语言·学习方法
en.en..1 小时前
冒泡排序与选择排序完整对比解析
开发语言·数据结构·算法·c#·排序算法
兰令水1 小时前
hot100【acm版】【2026.7.18打卡-java版本】
java·开发语言·算法
cui_ruicheng1 小时前
Python从入门到实战(十三):模块、包与环境管理
开发语言·python
就叫飞六吧1 小时前
子页面和dialog案例
开发语言·javascript·ecmascript