简体   繁体   中英

Generate .pb file without using protoc in golang

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 )?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM