在Golang中生成没有使用protoc的.pb文件。

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

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:

https://github.com/jhump/protoreflect/pull/354

huangapple
  • 本文由 发表于 2021年5月28日 23:41:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/67741875.html
匿名

发表评论

匿名网友

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

确定