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:


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 (

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

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

    // printing out raw object

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

    // check result

Save the file and run:

go run *.go

You should be able to see the results printed out:


Other Resource