cpp-httplib实现HTTP Server接收带参数的URL

文章详细解释了URL中不同符号的含义,如/用于目录分隔,?和&用于参数分隔,#表示书签。通过代码示例展示了如何在C++中使用httplib库处理GET请求的参数。文章强调了req.matches和req.params在获取URL信息时的区别,前者获取路径信息,后者获取参数。
摘要由CSDN通过智能技术生成

URL中符号意义

  • / 分隔目录和子目录

  • ?分隔实际的URL和参数

  • & URL中指定的参数间的分隔符

  • = URL中指定的参数的值

  • + 表示空格(在URL中不能使用空格)

  • # 表示书签

在RESTful风格的API中常见的URL样式:

  • 带时间路径的URL
    http://127.0.0.1:8080/Date/20230323173037
  • 使用 ? 符号的分隔符
    http://127.0.0.1:8080/Hld?date=20230323173037
  • 使用 & 符号带2个参数
    http://127.0.0.1:8080/Hld?date=20230323173037&date=20230366

代码演示获取参数:

#include <iostream>
#include <string>
#include <map>
#include <httplib.h>

using namespace std;
using namespace httplib;

int main()
{
    multimap<string, string> m = { {"HTTP0.9", "1991"}, {"HTTP1.0", "1996"}, {"HTTP1.1", "1999"} };

    for (multimap<string, string>::iterator it = m.begin(); it != m.end(); ++it)
    {
        cout << "[" << (*it).first << ", " << (*it).second << "]" << endl;
    }

    Server svr;
    svr.set_keep_alive_max_count(10);
    svr.set_keep_alive_timeout(10);
    svr.set_payload_max_length(1024 * 1024 * 512);

    svr.Get("/Hld", [&](const Request& req, Response& res) {

        cout << req.matches[0] << endl;
        cout << "params.size() = " << req.params.size() << endl;

        string context;
        for(std::multimap<std::string, std::string>::const_iterator it = req.params.begin(); it != req.params.end(); ++it)
        {
            string params = it->first + " = " + it->second;
            cout << params << endl;

            context += params += "\n";
        }

        res.set_content(context, "text/plain");
    });

    svr.set_error_handler([&](const Request& req, Response& res) {
        auto fmt = "<p>Error Status: <span style='color:red;'>%d</span></p>";
        char buf[BUFSIZ];
        snprintf(buf, sizeof(buf), fmt, res.status);
        res.set_content(buf, "text/html");
    });

    // Logging
    svr.set_logger([&](const Request& req, const Response& res) {
        for(std::multimap<std::string, std::string>::const_iterator it = req.params.begin(); it != req.params.end(); ++it)
        {
            string params = it->first + "=" + it->second;
            cout <<"[" << __FILE__ << ":" << __LINE__ << "] " << it->first << "=" << it->second << endl;
        }
    });

    svr.listen("0.0.0.0", 8080);

    return 0;
}

在这里插入图片描述

由于 ? 符号是分隔实际的URL和参数,所以 req.matches[0] 并不能获取到URL的参数,只能获得带路径的 / 符号后面的数据,而 req.params 才是获取URL的参数,理解URL才是理解代码的关键。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晓琴儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值