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

相关推荐
Halo_tjn2 分钟前
NIO 技术的使用
java·开发语言·nio
砍材农夫2 分钟前
物联网 基于netty核心实战-安全tls
java·开发语言·前端·物联网·安全
SEO_juper2 分钟前
JavaScript 渲染:AI 智能体无法读取,直接影响收录
开发语言·前端·javascript·aigc·seo·跨境电商·geo
Python+994 分钟前
C++ 内存模型 & 底层原理
java·jvm·c++
jllllyuz4 分钟前
通信信号调制识别系统(MATLAB实现)
开发语言·matlab
zincsweet6 分钟前
Linux 命名管道(FIFO)详解:原理分析、源码封装与通信流程图解
linux·服务器·c++·流程图
Kurisu5759 分钟前
深度解析:Java 对象的内存布局与指针压缩原理
java·开发语言
何何____20 分钟前
js的数据存储机制
开发语言·前端·javascript·ecmascript
夏天的峰没有风25 分钟前
Typora+gitcode+picgo搭建免费图床
开发语言·ios·swift
旺仔老馒头.28 分钟前
【C++】类和对象(三)
开发语言·c++·程序人生·类和对象