load_protobuf.hpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #pragma once
  2. #include <fcntl.h>
  3. #include <unistd.h>
  4. #include <iostream>
  5. #include <fstream>
  6. #include <google/protobuf/io/zero_copy_stream_impl.h>
  7. #include <google/protobuf/text_format.h>
  8. #include "google/protobuf/util/json_util.h"
  9. #include "error_code/error_code.hpp"
  10. using google::protobuf::io::FileInputStream;
  11. using google::protobuf::io::FileOutputStream;
  12. using google::protobuf::io::ZeroCopyInputStream;
  13. using google::protobuf::io::CodedInputStream;
  14. using google::protobuf::io::ZeroCopyOutputStream;
  15. using google::protobuf::io::CodedOutputStream;
  16. using google::protobuf::Message;
  17. static std::string getFileExtension(const std::string& file_path) {
  18. size_t dot_pos = file_path.find_last_of('.');
  19. if (dot_pos != std::string::npos && dot_pos < file_path.length() - 1) {
  20. return file_path.substr(dot_pos + 1);
  21. }
  22. return "";
  23. }
  24. static bool readTxtProtobufFile(const std::string &file_path, ::google::protobuf::Message& message)
  25. {
  26. int fd = open(file_path.c_str(), O_RDONLY);
  27. if (fd == -1) return false;
  28. auto* input = new FileInputStream(fd);
  29. bool success = google::protobuf::TextFormat::Parse(input, &message);
  30. delete input;
  31. close(fd);
  32. return success;
  33. }
  34. static bool readJsonProtobufFile(const std::string& file_path, ::google::protobuf::Message& message) {
  35. std::ifstream file(file_path);
  36. std::string json_data;
  37. if (file.is_open()) {
  38. // 将文件内容读取到字符串
  39. std::string line;
  40. while (std::getline(file, line)) {
  41. json_data += line;
  42. }
  43. file.close();
  44. } else {
  45. return false;
  46. }
  47. return google::protobuf::util::JsonStringToMessage(json_data, &message) == absl::OkStatus();
  48. }
  49. static Error_manager loadProtobufFile(const std::string &file, ::google::protobuf::Message &message) {
  50. std::string ext = getFileExtension(file);
  51. if (ext.empty()) {
  52. return {PARSE_FAILED, MINOR_ERROR, "prase protobuf file %s ext failed.", file.c_str()};
  53. }
  54. bool ret = false;
  55. if (ext == "prototxt") {
  56. ret = readTxtProtobufFile(file, message);
  57. } else if (ext == "json") {
  58. ret = readJsonProtobufFile(file, message);
  59. } else {
  60. return {PARSE_FAILED, MINOR_ERROR, "protobuf file %s type error.", file.c_str()};
  61. }
  62. if (ret) {
  63. return {SUCCESS, NORMAL, "prase protobuf file %s success.", file.c_str()};
  64. } else {
  65. return {PARSE_FAILED, MINOR_ERROR, "prase protobuf file %s failed.", file.c_str()};
  66. }
  67. }