README.md
1# Go support for Protocol Buffers - Google's data interchange format
2
3[![Build Status](https://travis-ci.org/golang/protobuf.svg?branch=master)](https://travis-ci.org/golang/protobuf)
4[![GoDoc](https://godoc.org/github.com/golang/protobuf?status.svg)](https://godoc.org/github.com/golang/protobuf)
5
6Google's data interchange format.
7Copyright 2010 The Go Authors.
8https://github.com/golang/protobuf
9
10This package and the code it generates requires at least Go 1.9.
11
12This software implements Go bindings for protocol buffers. For
13information about protocol buffers themselves, see
14 https://developers.google.com/protocol-buffers/
15
16## Installation ##
17
18To use this software, you must:
19- Install the standard C++ implementation of protocol buffers from
20 https://developers.google.com/protocol-buffers/
21- Of course, install the Go compiler and tools from
22 https://golang.org/
23 See
24 https://golang.org/doc/install
25 for details or, if you are using gccgo, follow the instructions at
26 https://golang.org/doc/install/gccgo
27- Grab the code from the repository and install the `proto` package.
28 The simplest way is to run:
29 ```
30 go get -u github.com/golang/protobuf/protoc-gen-go
31 ```
32 The compiler plugin, `protoc-gen-go`, will be installed in `$GOPATH/bin`
33 unless `$GOBIN` is set. It must be in your `$PATH` for the protocol
34 compiler, `protoc`, to find it.
35- If you need a particular version of `protoc-gen-go` (e.g., to match your
36 `proto` package version), one option is
37 ```shell
38 GIT_TAG="v1.2.0" # change as needed
39 go get -d -u github.com/golang/protobuf/protoc-gen-go
40 git -C "$(go env GOPATH)"/src/github.com/golang/protobuf checkout $GIT_TAG
41 go install github.com/golang/protobuf/protoc-gen-go
42 ```
43
44This software has two parts: a 'protocol compiler plugin' that
45generates Go source files that, once compiled, can access and manage
46protocol buffers; and a library that implements run-time support for
47encoding (marshaling), decoding (unmarshaling), and accessing protocol
48buffers.
49
50There is support for gRPC in Go using protocol buffers.
51See the note at the bottom of this file for details.
52
53There are no insertion points in the plugin.
54
55
56## Using protocol buffers with Go ##
57
58Once the software is installed, there are two steps to using it.
59First you must compile the protocol buffer definitions and then import
60them, with the support library, into your program.
61
62To compile the protocol buffer definition, run protoc with the --go_out
63parameter set to the directory you want to output the Go code to.
64
65 protoc --go_out=. *.proto
66
67The generated files will be suffixed .pb.go. See the Test code below
68for an example using such a file.
69
70## Packages and input paths ##
71
72The protocol buffer language has a concept of "packages" which does not
73correspond well to the Go notion of packages. In generated Go code,
74each source `.proto` file is associated with a single Go package. The
75name and import path for this package is specified with the `go_package`
76proto option:
77
78 option go_package = "github.com/golang/protobuf/ptypes/any";
79
80The protocol buffer compiler will attempt to derive a package name and
81import path if a `go_package` option is not present, but it is
82best to always specify one explicitly.
83
84There is a one-to-one relationship between source `.proto` files and
85generated `.pb.go` files, but any number of `.pb.go` files may be
86contained in the same Go package.
87
88The output name of a generated file is produced by replacing the
89`.proto` suffix with `.pb.go` (e.g., `foo.proto` produces `foo.pb.go`).
90However, the output directory is selected in one of two ways. Let
91us say we have `inputs/x.proto` with a `go_package` option of
92`github.com/golang/protobuf/p`. The corresponding output file may
93be:
94
95- Relative to the import path:
96
97```shell
98 protoc --go_out=. inputs/x.proto
99 # writes ./github.com/golang/protobuf/p/x.pb.go
100```
101
102 (This can work well with `--go_out=$GOPATH`.)
103
104- Relative to the input file:
105
106```shell
107protoc --go_out=paths=source_relative:. inputs/x.proto
108# generate ./inputs/x.pb.go
109```
110
111## Generated code ##
112
113The package comment for the proto library contains text describing
114the interface provided in Go for protocol buffers. Here is an edited
115version.
116
117The proto package converts data structures to and from the
118wire format of protocol buffers. It works in concert with the
119Go source code generated for .proto files by the protocol compiler.
120
121A summary of the properties of the protocol buffer interface
122for a protocol buffer variable v:
123
124 - Names are turned from camel_case to CamelCase for export.
125 - There are no methods on v to set fields; just treat
126 them as structure fields.
127 - There are getters that return a field's value if set,
128 and return the field's default value if unset.
129 The getters work even if the receiver is a nil message.
130 - The zero value for a struct is its correct initialization state.
131 All desired fields must be set before marshaling.
132 - A Reset() method will restore a protobuf struct to its zero state.
133 - Non-repeated fields are pointers to the values; nil means unset.
134 That is, optional or required field int32 f becomes F *int32.
135 - Repeated fields are slices.
136 - Helper functions are available to aid the setting of fields.
137 Helpers for getting values are superseded by the
138 GetFoo methods and their use is deprecated.
139 msg.Foo = proto.String("hello") // set field
140 - Constants are defined to hold the default values of all fields that
141 have them. They have the form Default_StructName_FieldName.
142 Because the getter methods handle defaulted values,
143 direct use of these constants should be rare.
144 - Enums are given type names and maps from names to values.
145 Enum values are prefixed with the enum's type name. Enum types have
146 a String method, and a Enum method to assist in message construction.
147 - Nested groups and enums have type names prefixed with the name of
148 the surrounding message type.
149 - Extensions are given descriptor names that start with E_,
150 followed by an underscore-delimited list of the nested messages
151 that contain it (if any) followed by the CamelCased name of the
152 extension field itself. HasExtension, ClearExtension, GetExtension
153 and SetExtension are functions for manipulating extensions.
154 - Oneof field sets are given a single field in their message,
155 with distinguished wrapper types for each possible field value.
156 - Marshal and Unmarshal are functions to encode and decode the wire format.
157
158When the .proto file specifies `syntax="proto3"`, there are some differences:
159
160 - Non-repeated fields of non-message type are values instead of pointers.
161 - Enum types do not get an Enum method.
162
163Consider file test.proto, containing
164
165```proto
166 syntax = "proto2";
167 package example;
168
169 enum FOO { X = 17; };
170
171 message Test {
172 required string label = 1;
173 optional int32 type = 2 [default=77];
174 repeated int64 reps = 3;
175 }
176```
177
178To create and play with a Test object from the example package,
179
180```go
181 package main
182
183 import (
184 "log"
185
186 "github.com/golang/protobuf/proto"
187 "path/to/example"
188 )
189
190 func main() {
191 test := &example.Test{
192 Label: proto.String("hello"),
193 Type: proto.Int32(17),
194 Reps: []int64{1, 2, 3},
195 }
196 data, err := proto.Marshal(test)
197 if err != nil {
198 log.Fatal("marshaling error: ", err)
199 }
200 newTest := &example.Test{}
201 err = proto.Unmarshal(data, newTest)
202 if err != nil {
203 log.Fatal("unmarshaling error: ", err)
204 }
205 // Now test and newTest contain the same data.
206 if test.GetLabel() != newTest.GetLabel() {
207 log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
208 }
209 // etc.
210 }
211```
212
213## Parameters ##
214
215To pass extra parameters to the plugin, use a comma-separated
216parameter list separated from the output directory by a colon:
217
218 protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto
219
220- `paths=(import | source_relative)` - specifies how the paths of
221 generated files are structured. See the "Packages and imports paths"
222 section above. The default is `import`.
223- `plugins=plugin1+plugin2` - specifies the list of sub-plugins to
224 load. The only plugin in this repo is `grpc`.
225- `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is
226 associated with Go package quux/shme. This is subject to the
227 import_prefix parameter.
228
229The following parameters are deprecated and should not be used:
230
231- `import_prefix=xxx` - a prefix that is added onto the beginning of
232 all imports.
233- `import_path=foo/bar` - used as the package if no input files
234 declare `go_package`. If it contains slashes, everything up to the
235 rightmost slash is ignored.
236
237## gRPC Support ##
238
239If a proto file specifies RPC services, protoc-gen-go can be instructed to
240generate code compatible with gRPC (http://www.grpc.io/). To do this, pass
241the `plugins` parameter to protoc-gen-go; the usual way is to insert it into
242the --go_out argument to protoc:
243
244 protoc --go_out=plugins=grpc:. *.proto
245
246## Compatibility ##
247
248The library and the generated code are expected to be stable over time.
249However, we reserve the right to make breaking changes without notice for the
250following reasons:
251
252- Security. A security issue in the specification or implementation may come to
253 light whose resolution requires breaking compatibility. We reserve the right
254 to address such security issues.
255- Unspecified behavior. There are some aspects of the Protocol Buffers
256 specification that are undefined. Programs that depend on such unspecified
257 behavior may break in future releases.
258- Specification errors or changes. If it becomes necessary to address an
259 inconsistency, incompleteness, or change in the Protocol Buffers
260 specification, resolving the issue could affect the meaning or legality of
261 existing programs. We reserve the right to address such issues, including
262 updating the implementations.
263- Bugs. If the library has a bug that violates the specification, a program
264 that depends on the buggy behavior may break if the bug is fixed. We reserve
265 the right to fix such bugs.
266- Adding methods or fields to generated structs. These may conflict with field
267 names that already exist in a schema, causing applications to break. When the
268 code generator encounters a field in the schema that would collide with a
269 generated field or method name, the code generator will append an underscore
270 to the generated field or method name.
271- Adding, removing, or changing methods or fields in generated structs that
272 start with `XXX`. These parts of the generated code are exported out of
273 necessity, but should not be considered part of the public API.
274- Adding, removing, or changing unexported symbols in generated code.
275
276Any breaking changes outside of these will be announced 6 months in advance to
277protobuf@googlegroups.com.
278
279You should, whenever possible, use generated code created by the `protoc-gen-go`
280tool built at the same commit as the `proto` package. The `proto` package
281declares package-level constants in the form `ProtoPackageIsVersionX`.
282Application code and generated code may depend on one of these constants to
283ensure that compilation will fail if the available version of the proto library
284is too old. Whenever we make a change to the generated code that requires newer
285library support, in the same commit we will increment the version number of the
286generated code and declare a new package-level constant whose name incorporates
287the latest version number. Removing a compatibility constant is considered a
288breaking change and would be subject to the announcement policy stated above.
289
290The `protoc-gen-go/generator` package exposes a plugin interface,
291which is used by the gRPC code generation. This interface is not
292supported and is subject to incompatible changes without notice.
293