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
#include
#include
#include using namespace std;
using namespace httplib;int main()
{multimap<string, string> m &#61; { {"HTTP0.9", "1991"}, {"HTTP1.0", "1996"}, {"HTTP1.1", "1999"} };for (multimap<string, string>::iterator it &#61; m.begin(); it !&#61; m.end(); &#43;&#43;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() &#61; " << req.params.size() << endl;string context;for(std::multimap<std::string, std::string>::const_iterator it &#61; req.params.begin(); it !&#61; req.params.end(); &#43;&#43;it){string params &#61; it->first &#43; " &#61; " &#43; it->second;cout << params << endl;context &#43;&#61; params &#43;&#61; "\n";}res.set_content(context, "text/plain");});svr.set_error_handler([&](const Request& req, Response& res) {auto fmt &#61; "Error Status: %d
";char buf[BUFSIZ];snprintf(buf, sizeof(buf), fmt, res.status);res.set_content(buf, "text/html");});svr.set_logger([&](const Request& req, const Response& res) {for(std::multimap<std::string, std::string>::const_iterator it &#61; req.params.begin(); it !&#61; req.params.end(); &#43;&#43;it){string params &#61; it->first &#43; "&#61;" &#43; it->second;cout <<"[" << __FILE__ << ":" << __LINE__ << "] " << it->first << "&#61;" << it->second << endl;}});svr.listen("0.0.0.0", 8080);return 0;
}
由于 ? 符号是分隔实际的URL和参数&#xff0c;所以 req.matches[0] 并不能获取到URL的参数&#xff0c;只能获得带路径的 / 符号后面的数据&#xff0c;而 req.params 才是获取URL的参数&#xff0c;理解URL才是理解代码的关键。