Skip to content

Instantly share code, notes, and snippets.

@rich840213
Forked from miguelmota/example.proto
Created October 13, 2022 06:14
Show Gist options
  • Save rich840213/990f4ee11c87a9a2758802a78ad8a18a to your computer and use it in GitHub Desktop.
Save rich840213/990f4ee11c87a9a2758802a78ad8a18a 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