英文:
Generate .pb file without using protoc in golang
问题
你好!根据你的要求,我将为你翻译以下内容:
我正在尝试使用service.proto作为文件输入,在Go语言中生成.pb.go文件。
是否有一种方法可以在不使用protoc二进制文件的情况下完成(比如直接使用github.com/golang/protobuf/protoc-gen-go包)?
英文:
I'm trying to generate .pb.go file using service.proto as file input in Go.
Is there a way to do it without using protoc binary (like directly using package github.com/golang/protobuf/protoc-gen-go)?
答案1
得分: 2
如果你有一个像这样的detail.proto文件:
message AppDetails {
   optional string version = 4;
}
你可以像这样将其解析为一个消息:
package main
import (
   "fmt"
   "github.com/golang/protobuf/proto"
   "github.com/jhump/protoreflect/desc/protoparse"
   "github.com/jhump/protoreflect/dynamic"
)
func parse(file, msg string) (*dynamic.Message, error) {
   var p protoparse.Parser
   fd, err := p.ParseFiles(file)
   if err != nil {
      return nil, err
   }
   md := fd[0].FindMessage(msg)
   return dynamic.NewMessage(md), nil
}
func main() {
   b := []byte("\n\vhello world")
   m, err := parse("detail.proto", "AppDetails")
   if err != nil {
      panic(err)
   }
   if err := proto.Unmarshal(b, m); err != nil {
      panic(err)
   }
   fmt.Println(m) // version:"hello world"
}
然而,你可能会注意到,这个包仍在使用旧的Protobuf V1。我找到了一个关于V2的Pull Request:
https://github.com/jhump/protoreflect/pull/354
英文:
If you have a detail.proto like this:
message AppDetails {
   optional string version = 4;
}
You can parse it into a message like this:
package main
import (
   "fmt"
   "github.com/golang/protobuf/proto"
   "github.com/jhump/protoreflect/desc/protoparse"
   "github.com/jhump/protoreflect/dynamic"
)
func parse(file, msg string) (*dynamic.Message, error) {
   var p protoparse.Parser
   fd, err := p.ParseFiles(file)
   if err != nil {
      return nil, err
   }
   md := fd[0].FindMessage(msg)
   return dynamic.NewMessage(md), nil
}
func main() {
   b := []byte("\"\vhello world")
   m, err := parse("detail.proto", "AppDetails")
   if err != nil {
      panic(err)
   }
   if err := proto.Unmarshal(b, m); err != nil {
      panic(err)
   }
   fmt.Println(m) // version:"hello world"
}
However you may notice, this package is still using the old Protobuf V1. I did
find a Pull Request for V2:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论