#pragma once #include #include #include #include #include #include #include "google/protobuf/util/json_util.h" #include "error_code/error_code.hpp" using google::protobuf::io::FileInputStream; using google::protobuf::io::FileOutputStream; using google::protobuf::io::ZeroCopyInputStream; using google::protobuf::io::CodedInputStream; using google::protobuf::io::ZeroCopyOutputStream; using google::protobuf::io::CodedOutputStream; using google::protobuf::Message; static std::string getFileExtension(const std::string& file_path) { size_t dot_pos = file_path.find_last_of('.'); if (dot_pos != std::string::npos && dot_pos < file_path.length() - 1) { return file_path.substr(dot_pos + 1); } return ""; } static bool readTxtProtobufFile(const std::string &file_path, ::google::protobuf::Message& message) { int fd = open(file_path.c_str(), O_RDONLY); if (fd == -1) return false; auto* input = new FileInputStream(fd); bool success = google::protobuf::TextFormat::Parse(input, &message); delete input; close(fd); return success; } static bool readJsonProtobufFile(const std::string& file_path, ::google::protobuf::Message& message) { std::ifstream file(file_path); std::string json_data; if (file.is_open()) { // 将文件内容读取到字符串 std::string line; while (std::getline(file, line)) { json_data += line; } file.close(); } else { return false; } return google::protobuf::util::JsonStringToMessage(json_data, &message) == absl::OkStatus(); } static Error_manager loadProtobufFile(const std::string &file, ::google::protobuf::Message &message) { std::string ext = getFileExtension(file); if (ext.empty()) { return {PARSE_FAILED, MINOR_ERROR, "prase protobuf file %s ext failed.", file.c_str()}; } bool ret = false; if (ext == "prototxt") { ret = readTxtProtobufFile(file, message); } else if (ext == "json") { ret = readJsonProtobufFile(file, message); } else { return {PARSE_FAILED, MINOR_ERROR, "protobuf file %s type error.", file.c_str()}; } if (ret) { return {SUCCESS, NORMAL, "prase protobuf file %s success.", file.c_str()}; } else { return {PARSE_FAILED, MINOR_ERROR, "prase protobuf file %s failed.", file.c_str()}; } }