Skip to content

Instantly share code, notes, and snippets.

@jr-md
Last active September 2, 2019 09:44
Show Gist options
  • Select an option

  • Save jr-md/f9267711862441406c77e21ce48b660e to your computer and use it in GitHub Desktop.

Select an option

Save jr-md/f9267711862441406c77e21ce48b660e to your computer and use it in GitHub Desktop.
protocol buffers

proto example

Install and run

  • install protoc (google for download)
  • clone repo
  • go get ./...
  • make
  • go run proto-main.go
.PHONY: gen_protos
gen_protos:
protoc -I=./ --go_out=./generatedprotos/ ./person.proto
syntax = "proto3";
package main;
message Person {
string nickname = 1;
enum Status {
Unknown = 0;
Active = 1;
Disabled = 2;
}
Status status = 3;
string secondNickname = 4;
}
package main
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"os"
"time"
"github.com/gogo/protobuf/proto"
)
func main() {
fileName := time.Now().Format(time.Kitchen)
write(fileName)
read(fileName)
}
func write(fileName string) {
file, err := os.Create(fileName)
if err != nil {
panic(err)
}
defer file.Close()
person := &Person{
Nickname: "Johnny",
Status: Person_Disabled,
}
b, err := proto.Marshal(person)
if err != nil {
panic(err)
}
_, err = io.Copy(file, bytes.NewBuffer(b))
if err != nil {
panic(err)
}
}
func read(fileName string) {
file, err := os.Open(fileName)
if err != nil {
panic(err)
}
defer file.Close()
b, err := ioutil.ReadAll(file)
if err != nil {
panic(err)
}
person := new(Person)
err = proto.Unmarshal(b, person)
if err != nil {
panic(err)
}
json.NewEncoder(os.Stderr).Encode(person)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment