Generate .pb file without using protoc in golang

1.3k views Asked by At

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

There are 1 answers

4
Zombo On

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