【发布时间】:2012-02-05 10:58:12
【问题描述】:
我想在我的应用程序上公开一个 REST API,使用 Mongoose Web 服务器并为不同的查询提供处理程序。
查询的一个例子是这样的(我现在只使用 GET,其余的 HTTP 动词稍后会出现):
GET /items -> returns a list of all items in JSON
GET /item/by/handle/123456789 -> returns item that has handle 123456789
GET /item/by/name/My%20Item -> returns item(s) that have the name "My Item"
我很好奇应该如何实现这些查询的解析。我可以轻松解析第一个,因为这只是if( query.getURI() == "/items") return ... 的问题。
但是对于接下来的两个查询,我必须以完全不同的方式操作 std:: 字符串,使用一些 std::string::find() 魔法和偏移量来获取参数。
例如,这是我对第二个查询的实现:
size_t position = std::string::npos;
std::string path = "/item/by/handle/";
if( (position = query.getURI().find(path) ) != std::string::npos )
{
std::string argument = query.getURI().substr( position + path.size() );
// now parse the argument to an integer, find the item and return it
}
如果我想“模板化”这个怎么办?含义:我描述了路径和之后我期望的参数(一个整数,一个字符串,....);并且自动生成代码来处理这个?
Tl;Dr:我希望能够在 C++ 中处理 REST 查询,其中包含以下内容:
registerHandler( "/item/by/handle/[INTEGER]", myHandlerMethod( int ));
这可能吗?
【问题讨论】:
-
听起来你需要正则表达式,就像在 boost 或 C++11 中找到的那样。
标签: c++ rest parsing mongoose-web-server