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

相关推荐
闻缺陷则喜何志丹11 分钟前
【拆位法】P8743 [蓝桥杯 2021 省 A] 异或数列|普及+
c++·蓝桥杯·位运算·拆位法
fpcc26 分钟前
跟我学C++中级篇——Concepts的循环依赖
c++·模板和元编程
Web打印31 分钟前
Phpask(php集成环境)之16 怎样彻底停用一个网站
开发语言·php
临水逸39 分钟前
飞牛fnos 2025 漏洞Java跨域URL浏览器
java·开发语言·安全·web安全
H Corey42 分钟前
数据结构与算法:高效编程的核心
java·开发语言·数据结构·算法
訫悦1 小时前
C++自带的set get语法(MSVC)
开发语言·c++
SmartBrain1 小时前
Python 特性(第一部分):知识点讲解(含示例)
开发语言·人工智能·python·算法
墨雪不会编程1 小时前
C++之【list详解篇一】如何玩好链表
c++·链表·list
01二进制代码漫游日记1 小时前
自定义类型:联合和枚举(一)
c语言·开发语言·学习·算法
柏木乃一2 小时前
Linux进程信号(2):信号产生part2
linux·运维·服务器·c++·信号处理·信号·异常