Skip to content

Instantly share code, notes, and snippets.

@michaeljs1990
Forked from miguelmota/example.proto
Created July 28, 2020 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaeljs1990/114d6573b9d7cedd4f2f001894026987 to your computer and use it in GitHub Desktop.
Save michaeljs1990/114d6573b9d7cedd4f2f001894026987 to your computer and use it in GitHub Desktop.
Golang protobuf marshal and unmarshal example
syntax = "proto3";
message Message {
bytes text = 1;
}
package main
import (
fmt "fmt"
"./example"
"github.com/golang/protobuf/proto"
)
func main() {
var text = []byte("hello")
message := &example.Message{
Text: text,
}
data, err := proto.Marshal(message)
if err != nil {
panic(err)
}
fmt.Println(data) // [10 5 104 101 108 108 111]
newMessage := &example.Message{}
err = proto.Unmarshal(data, newMessage)
if err != nil {
panic(err)
}
fmt.Println(newMessage.GetText()) // [104 101 108 108 111]
}
protoc --go_out=example example.proto
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment