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才是理解代码的关键。