我对 C++ 很陌生,无法理解 Crow Web 服务器的文档。
我想要的是模拟 RPC 端点,允许查询参数为空,如果是这样,则默认它们为“”。使用 .get(value, defaultStr) 的想法似乎缺失或消失了..
我什至要求一个不存在的参数,并且没有选项来设置我在文档中看到的默认值。
(用 Flask 标记,因为 Crow 似乎是基于它的)
这是我所拥有的:
CROW_ROUTE(api, "/rpc")
.methods(crow::HTTPMethod::Get)([&rpcParser](const crow::request &req) {
// Extract query parameters
std::string method = req.url_params.get("method");
std::string key = req.url_params.get("key");
std::string value = req.url_params.get("value");
// Check if any of the parameters are missing
if (method.empty()) {
return crow::response(400, "Missing required query parameters");
}
if (key.empty())
key = "";
if (value.empty())
value = "";
// Split the method at the first dot
size_t dot_pos = method.find('.');
if (dot_pos != std::string::npos) {
std::string class_name = method.substr(0, dot_pos); // Extract the part before the dot
std::string method_name = method.substr(dot_pos + 1); // Extract the part after the dot
// Call the RPC parser with the split values
rpcParser.parse(class_name, method_name, key, value);
} else {
// Handle the error when there is no dot in the method
// For example, you might want to send an error response
return crow::response(400, "Invalid method format");
}
// Return a response
return crow::response(200, "Request processed successfully");
});
给自己和他人的注意事项:
.get() 返回 char* ,而不是 std:string
简单的出路(可能是更漂亮的方法):
std::string method = req.url_params.get("method") ? req.url_params.get("method") : "";
std::string key = req.url_params.get("key") ? req.url_params.get("key") : "";
std::string value = req.url_params.get("value") ? req.url_params.get("value") : "";