A Quick Start on Protocol Buffer with Go


Create a .proto file

First, we need to install buffer protocol tool:

# Protocol Buffer compiling tool
brew install protobuf

# With Go plugin
go get -u github.com/golang/protobuf/protoc-gen-go

Then we create a quick example file, like person.proto:

syntax="proto3";

package main;

message Person {
  string name = 2;
  int32 age = 3;
}

After that, we compile the file by running:

protoc --go_out=. *.proto

which generates a person.pb.proto file.

Use the protocol in Go code

Then with that file, we do:

package main

import (
    "github.com/golang/protobuf/proto"
)

func main() {
    person := &Person{
        Name: "Adler",
        Age:  30,
    }

    data, err := proto.Marshal(person)
    if err != nil {
        log.Fatal("Error: ", err)
    }

    // printing out raw object
    fmt.Println(data)

    // bind data to a new object
    newPerson := &Person{}
    err = proto.Unmarshal(data, newPerson)
    if err != nil {
        log.Fatal("Error: ", err)
    }

    // check result
    fmt.Println(newPerson.GetAge())
    fmt.Println(newPerson.GetName())
}

Save the file and run:

go run *.go

You should be able to see the results printed out:

Adler
30

Other Resource