1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
# proto
[](https://github.com/emicklei/proto/actions/workflows/go.yml)
[](https://goreportcard.com/report/github.com/emicklei/proto)
[](https://pkg.go.dev/github.com/emicklei/proto)
[](https://codecov.io/gh/emicklei/proto)
Package in Go for parsing Google Protocol Buffers [.proto files version 2 + 3](https://developers.google.com/protocol-buffers/docs/reference/proto3-spec)
### install
go get -u -v github.com/emicklei/proto
### usage
package main
import (
"fmt"
"os"
"github.com/emicklei/proto"
)
func main() {
reader, _ := os.Open("test.proto")
defer reader.Close()
parser := proto.NewParser(reader)
definition, _ := parser.Parse()
proto.Walk(definition,
proto.WithService(handleService),
proto.WithMessage(handleMessage))
}
func handleService(s *proto.Service) {
fmt.Println(s.Name)
}
func handleMessage(m *proto.Message) {
lister := new(optionLister)
for _, each := range m.Elements {
each.Accept(lister)
}
fmt.Println(m.Name)
}
type optionLister struct {
proto.NoopVisitor
}
func (l optionLister) VisitOption(o *proto.Option) {
fmt.Println(o.Name)
}
### validation
Current parser implementation is not completely validating `.proto` definitions.
In many but not all cases, the parser will report syntax errors when reading unexpected charaters or tokens.
Use some linting tools (e.g. https://github.com/uber/prototool) or `protoc` for full validation.
### contributions
See [proto-contrib](https://github.com/emicklei/proto-contrib) for other contributions on top of this package such as protofmt, proto2xsd and proto2gql.
[protobuf2map](https://github.com/emicklei/protobuf2map) is a small package for inspecting serialized protobuf messages using its `.proto` definition.
© 2017-2022, [ernestmicklei.com](http://ernestmicklei.com). MIT License. Contributions welcome.
|