在C++中解析REST查询

Gui*_*i13 5 c++ rest parsing mongoose-web-server

我想在我的应用程序上公开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"
Run Code Online (Sandbox Code Playgroud)

我很好奇的是我应该如何实现这些查询的解析.我可以很容易地解析第一个,因为它只是一个问题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
}
Run Code Online (Sandbox Code Playgroud)

如果我想"模仿"这个怎么办?含义:我描述了之后我想要的路径和参数(一个整数,一个字符串,......); 并自动生成代码来处理这个?

Tl; Dr:我希望能够使用以下内容处理C++中的REST查询:

registerHandler( "/item/by/handle/[INTEGER]", myHandlerMethod( int ));
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Tom*_*Tom 5

一个相当不性感但简单的方法是简单地使用 sscanf。请原谅相当类似 C 的代码。请注意,这不提供您正在寻找的那种语法,但它不需要任何库、扩展或增强。

例如,

int param;
int a, b;
char c[255];

/* recall that sscanf returns the number of variables filled */
if( 1 == sscanf( query.getURI(), "/item/by/handle/%d", &param ) ) {

  handler( param );

} else if ( 3 == sscanf( query.getURI(), "/more/params/%d/%d/%s", &a, &b, &c ) ) {

  anotherHandler( a, b, c );

} else {
  // 404
}

  • 请注意,使用 %s 对用户输入是危险的,因为它不会检查边界并且很容易溢出。我建议上面的例子:`sscanf(query.getURI(), "/more/params/%d/%d/%254s", &a, &b, c)` (2认同)