如何在Golang中将.proto文件解析为FileDescriptor?

huangapple go评论102阅读模式
英文:

how to parse .proto file into FileDescriptor in golang?

问题

我的目标是动态地从.proto文件中获取FileDescriptor,我应该如何做呢?

输入:

syntax = "proto3";

package "halo";

message SearchRequest {
	string query = 1;
	string data = 2;
}

输出:

import "google.golang.org/protobuf/types/descriptorpb"

descriptorpb.FileDescriptorProto{
    Package: "halo",
    MessageType: []{
        descriptorpb.DescriptorProto{query},
        descriptorpb.DescriptorProto{data},
    }
}
英文:

My goal is to get FileDescriptor from .proto file dynamically, how should I do it?

input:

syntax = "proto3";

package "halo";

message SearchRequest {
	string query = 1;
	string data = 2;
}

output:

import 	"google.golang.org/protobuf/types/descriptorpb"

descriptorpb.FileDescriptorProto{
    Package: "halo",
    MessageType: []{
        descriptorpb.DescriptorProto{query},
        descriptorpb.DescriptorProto{data},
    }
}

答案1

得分: 2

除非为您的平台存在特定的运行时/库解析器,否则最简单的方法是使用protoc命令和-oFILE / --descriptor_set_out=FILE选项,该选项解析模式并输出一个序列化的FileDescriptorSet内容的protobuf负载。您可以在特定的平台上反序列化此内容,并获取第一个(通常是唯一的)文件。对于这个反序列化步骤,您通常会使用protoc命令,以descriptor.proto模式作为输入,以获取该模式的特定于平台/语言的解析器。

特定于平台的运行时/库解析器并不常见,通常更常见于第三方工具;Google的golang protobuf实现是一方面的,据我所知,golang没有这样的解析器。

英文:

Unless a platform-specific runtime/library parser exists for your platform, the simplest way to do this is to use protoc with the -oFILE / --descriptor_set_out=FILE option, which parses the schema and outputs a protobuf payload that is the serialized FileDescriptorSet contents. You would deserialize this in your specific platform, and take the first (usually only) file. For this deserialize step, you would typically use protoc with the descriptor.proto schema as input, to get a platform/language-specific parser for that schema.

Platform-specific runtime/library parsers aren't common, and tend to be more common in 3rd-party tooling; the Google golang protobuf implementation is 1st-party, and no such parser exists for golang AFAIK.

huangapple
  • 本文由 发表于 2022年1月10日 21:32:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/70653232.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定