在C ++中解析REST查询 [英] Parse REST query in C++

查看:94
本文介绍了在C ++中解析REST查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Mongoose 网络服务器在我的应用程序上公开REST API,并提供处理程序不同的查询.

I'd like to expose a REST API on my application, using the Mongoose web server and providing handlers for different queries.

一个查询示例将是这样的(目前我仅使用GET,其余的HTTP动词稍后会出现):

An example of query would be like this (I'm only using GET for the moment, the rest of HTTP verbs will come later):

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()魔术和偏移量来获取参数.

What I'm curious is how I should implement the parsing of these queries. I can easily parse the first, since it is simply a matter of if( query.getURI() == "/items") return ....
But for the next two queries, I have to manipulate std:: strings in a whole different way, using some std::string::find() magic and offsets to get to the argument.

作为一个例子,这是我对第二个查询的实现:

As an example, this is the implementation I have for the second query:

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
}

如果我想对此模板化"怎么办?含义:我描述了以后的路径和参数(整数,字符串,...);并自动生成代码来处理此问题?

What if I want to "templatize" this; meaning: I describe the path and the arguments I expect afterwards (an integer, a string, ....); and the code is automatically generated to handle this?

Tl;博士:我希望能够通过以下方式处理C ++中的REST查询:

Tl;Dr: I want to be able to handle REST queries in C++ with something along these lines:

registerHandler( "/item/by/handle/[INTEGER]", myHandlerMethod( int ));

这可能吗?

推荐答案

一种不太性感但简单的方法是简单地使用sscanf.请原谅类似C的代码.请注意,它不提供您要查找的语法,但不需要任何库,扩展名或boost.

A rather un-sexy, yet simple approach would be to simply use sscanf. Pardon the rather C-like code. Note, this doesn't provide the sort of syntax you're looking for, but it doesn't require any libraries, extensions, or boost.

例如,


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
}

这篇关于在C ++中解析REST查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆