基本可用。

This commit is contained in:
2026-03-10 14:32:11 +08:00
parent b24bc8a75d
commit d2fc41496e
13 changed files with 302 additions and 42 deletions

View File

@@ -1,6 +1,7 @@
#include "bf.request.h"
#include <fmt/format.h>
#include <nlohmann/json.hpp>
#include "bf.util.h"
@@ -58,4 +59,62 @@ size_t BF_Request::writeData(void* buffer, size_t size, size_t nmemb, std::strin
auto totalSize = size * nmemb;
str->append(static_cast<char*>(buffer), totalSize);
return totalSize;
}
bool BF_Request::HandleStr(const std::string& jsonMsg, std::string& out)
{
out.clear();
if (jsonMsg.empty()) {
gLogger->error("JSON消息为空");
return false;
}
try {
nlohmann::json j = nlohmann::json::parse(jsonMsg);
if (j.contains("error_code")) {
std::string errorCode = j["error_code"];
std::string errorMsg = j.value("error_msg", "未知错误");
gLogger->error("翻译API返回错误: code={}, msg={}", errorCode, errorMsg);
return false;
}
if (!j.contains("trans_result")) {
gLogger->error("JSON中缺少trans_result字段");
return false;
}
const auto& transResult = j["trans_result"];
if (!transResult.is_array() || transResult.empty()) {
gLogger->error("trans_result不是有效数组或为空");
return false;
}
std::vector<std::string> translations;
for (const auto& item : transResult) {
if (item.contains("dst")) {
translations.push_back(item["dst"].get<std::string>());
}
}
if (translations.empty()) {
gLogger->error("未找到有效的翻译结果");
return false;
}
for (size_t i = 0; i < translations.size(); ++i) {
out += translations[i];
if (i < translations.size() - 1) {
out += "\n";
}
}
return true;
} catch (const nlohmann::json::exception& e) {
gLogger->error("JSON解析失败: {}, 原始数据: {}", e.what(), jsonMsg);
return false;
} catch (const std::exception& e) {
gLogger->error("处理JSON时发生异常: {}, 原始数据: {}", e.what(), jsonMsg);
return false;
}
}