without any theory about serialization i will simply introduce how to quick start using protobuf in golang
you can download in https://github.com/protocolbuffers/protobuf/releases
recommend release (proto3 with latest tag)
unzip file and move protoc program to your $PATH, /usr/local/bin
for example
protoc cannot compile your proto file to golang version without plugin
download the plugin with following script
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
make sure your go program path is registered.
// filename: example.proto
syntax = "proto3";
package example;
option go_package = "./example_pb";
// refer to https://developers.google.com/protocol-buffers/docs/proto3
enum Career {
TEACHER = 0;
POLICE = 1;
DOCTOR = 2;
NONE = 3;
}
message Person {
string name = 1;
int32 id_card = 2;
string email = 3;
bool is_adult = 4;
repeated int32 phone_number_list = 5;
Career career = 6;
}
now you can compile your proto file to a go version
protoc --go_out=. example.proto
everything is ready, try marshal and unmarshal with protobuf
package main
import (
"encoding/json"
"fmt"
"log"
"my_pb/example_pb"
"google.golang.org/protobuf/proto"
)
func main() {
example()
}
func example() {
// marshal
person := &example_pb.Person{
Name: "John",
IdCard: 231421,
Email: "mitjohn@gmail.com",
IsAdult: true,
PhoneNumberList: []int32{123, 456, 789},
Career: example_pb.Career_TEACHER,
}
bytes, err := proto.Marshal(person)
if err != nil {
log.Fatal("marshaling error: ", err)
}
fmt.Println("protobuf:", bytes)
// unmarshal
getPerson := &example_pb.Person{}
err = proto.Unmarshal(bytes, getPerson)
if err != nil {
log.Fatal("unmarshaling error: ", err)
}
s, _ := json.MarshalIndent(getPerson, "", " ")
fmt.Printf("person: %s\n", string(s))
fmt.Printf("career: %s\n", getPerson.GetCareer())
}
you will get