Protocol Buffers (Protobuf) is a language- and platform-neutral data serialization format developed by Google. It allows you to define data structures in a .proto file and then use code generation tools to generate code in various languages for working with those data structures.
To use Protobuf with Go, you’ll need to do the following:
Install the Protobuf compiler (protoc) and the Go Protobuf plugin:
# Install protoc
wget https://github.com/protocolbuffers/protobuf/releases/download/v3.14.0/protoc-3.14.0-linux-x86_64.zip
unzip protoc-3.14.0-linux-x86_64.zip -d protoc3
sudo mv protoc3/bin/* /usr/local/bin/
# Install the Go Protobuf plugin
go get -u github.com/golang/protobuf/protoc-gen-go
Define your data structures in a .proto file. For example:
syntax = "proto3";
package example;
message Person {
string name = 1;
int32 age = 2;
bool is_employee = 3;
}
message Address {
string street = 1;
string city = 2;
string state = 3;
string zip = 4;
}
Use the Protobuf compiler to generate Go code from your .proto file:
protoc --go_out=. example.proto
This will generate a Go file named example.pb.go that contains code for working with the data structures you defined in your .proto file.
Import the generated code and use it in your Go program. For example:
package main
import (
"fmt"
"example"
)
func main() {
// Create a new Person object
p := example.Person{
Name: "John Smith",
Age: 30,
IsEmployee: true,
Addresses: []*example.Address{
&example.Address{
Street: "123 Main Street",
City: "New York",
State: "NY",
Zip: "10001",
},
&example.Address{
Street: "456 Market Street",
City: "San Francisco",
State: "CA",
Zip: "94111",
},
},
}
// Serialize the object to a Protobuf-encoded byte slice
data, err := p.Marshal()
if err != nil {
fmt.Println(err)
return
}
// Deserialize the byte slice back into a new Person object
var p2 example.Person
if err := p2.Unmarshal(data); err != nil {
fmt.Println(err)
return
}
fmt.Println(p2.Name, p2.Age, p2.IsEmployee)
for _, addr := range p2.Addresses {
fmt.Println(addr.Street, addr.City, addr.State, addr.Zip)
}
}
In this example, we define a Person data structure with a name, age, and a list of addresses in a .proto file. We then use the Protobuf compiler to generate Go code for working with these data structures.
In the Go code, we create a new Person object and serialize it to a Protobuf-encoded byte slice using the Marshal method. We then deserialize the byte slice back into a new Person object using the Unmarshal method. Finally, we print the deserialized object’s name, age, and list of addresses to the console.
I hope this helps give you an idea of how to use Protobuf with Go. You can find more detailed documentation and examples in the Protobuf documentation.