Protocol Buffers Data Type Go Code Generation: Difference between revisions
Line 20: | Line 20: | ||
=Code Generation= | =Code Generation= | ||
The compiler | The compiler requires a mandatory source directory, specified with <code>--proto_path</code>, where it expects the find the <code>.proto</code> Protocol Buffer files. The Protocol Buffer files are individually specified on the command line, and each <code>.proto</code> file must be listed as relative to <code>--proto_path</code>. | ||
<syntaxhighlight lang='bash'> | <syntaxhighlight lang='bash'> | ||
protoc \ | protoc \ | ||
--proto_path= | --proto_path=<protocol-buffer-source-directory> \ | ||
--go_out=./pkg/person \ | --go_out=./pkg/person \ | ||
--go_opt=Mperson.proto=. \ | --go_opt=Mperson.proto=. \ | ||
. | <protocol-buffer-file-1>.proto <protocol-buffer-file-1>.proto ... | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 17:42, 7 May 2024
External
https://protobuf.dev/reference/go/go-generated
Internal
Overview
Protocol Buffer files are processed by the Protocol Buffer compiler protoc
, which needs the Go plugin protoc-gen-go
to generate Go code. The plugin is installed as described in the Installation section below. The protoc
command line details are discussed in the Code Generation section.
Installation
The generic compiler must be installed with TODO.
To generate Go code, the Go plugin must be installed with:
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
This will install a protoc-gen-go
binary in ${GOBIN}
.
Code Generation
The compiler requires a mandatory source directory, specified with --proto_path
, where it expects the find the .proto
Protocol Buffer files. The Protocol Buffer files are individually specified on the command line, and each .proto
file must be listed as relative to --proto_path
.
protoc \
--proto_path=<protocol-buffer-source-directory> \
--go_out=./pkg/person \
--go_opt=Mperson.proto=. \
<protocol-buffer-file-1>.proto <protocol-buffer-file-1>.proto ...
The compiler creates a single source file for each .proto
command line-provided input file. The name of the output file is the name of the corresponding .proto
file where the .proto
extension is replaced with .pb.go
. The newly created files will be placed under the directory specified by --go_out
, but where exactly depends on the --go_opt
compiler flags, as shown below. In the example above, a ./pkg/person/person.pb.go
file will be created.
Arguments
--proto_path
The directory where to find the Protocol Buffer files. The individual Protocol Buffer files specified on the command line must be relative to this directory.
--go_out
The directory where the compiler writes the Go output. Where exactly in the directory depends on the value of the --go-opt
value.