Skip to content

Instantly share code, notes, and snippets.

@rsgok
Last active April 16, 2022 07:11
Show Gist options
  • Save rsgok/2200613b134aa4ccfd1ca742143863b4 to your computer and use it in GitHub Desktop.
Save rsgok/2200613b134aa4ccfd1ca742143863b4 to your computer and use it in GitHub Desktop.
protobuf quick start

how to use protobuf

without any theory about serialization i will simply introduce how to quick start using protobuf in golang

step by step

prepare environment

download protobuf

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

download golang plugin

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.

write proto file

// 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;
}

compile to go

now you can compile your proto file to a go version

protoc --go_out=. example.proto

use protobuf

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

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment