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

相关推荐
码客-ygluu7 小时前
X3 LUA 异步分布式微服务集群框架
c++·架构·lua
starzy19908 小时前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
M--Y8 小时前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
九英里路10 小时前
protobuf快速上手
网络·c++·中间件·json·谷歌·序列化·protobuf
吴可可12310 小时前
WScript Shell操作注册表详解
开发语言
纪念 22910 小时前
C++ 算法基础 (差分)
开发语言·c++·算法
码农小河6615 小时前
基于PHP的电商后台蜜罐系统
开发语言·php
starzy199015 小时前
深入理解Scala柯里化函数:函数链式变换
开发语言·scala
ShineWinsu15 小时前
对于Qt:QTreeWidget常见属性以及QTreeWidgetItem类的解析
开发语言·c++·qt·gui·客户端·多叉树·qtreewidget
落羽的落羽16 小时前
【C++】C++17的主要特性
linux·服务器·开发语言·c++·算法·机器学习