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