Code generation

In order to generate the code from a .proto file, you need the protoc application and the official proto generation package:

go get -u github.com/golang/protobuf/protoc-gen-go

The installed package comes with the protoc-gen-go command; this enables the protoc command to use the --go_out flag to produce Go source files in the desired folders. Version 1.4 of Go can specify special comments for automatic generation of code with its go generate command, and these comments start with //go:generate followed by the command, as in the following example:

//go:generate protoc -I=$SRC_PATH --go_out=$DST_DIR source.proto

It enables us to specify a source path for import lookup, output directory, and a source file. The paths are relative to the package directory where the comment is found and it can be invoked with the go generate $pkg command.

Let's start with a simple .proto file:

syntax = "proto3";

message Character {
string name = 1;
string surname = 2;
string job = 3;
int32 year_of_birth = 4;
}

And let's create a Go source file in the same folder with the comment for generating the code:

package gen

//go:generate protoc --go_out=. char.proto

Now, we can generate the go command that will produce a file with the same name as the .proto file and the .pb.go extension. The file will contain Go sources for the types and services defined in the .proto file:

// Code generated by protoc-gen-go. DO NOT EDIT.
// source: char.proto
...
type Character struct {
Name string `protobuf:"bytes,1,opt,name=name"`
Surname string `protobuf:"bytes,2,opt,name=surname"`
Job string `protobuf:"bytes,3,opt,name=job" json:"job,omitempty"`
YearOfBirth int32 `protobuf:"varint,4,opt,name=year_of_birth,json=yearOfBirth"`
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.20.224.107