Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active September 20, 2023 02:07
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save miguelmota/25568433ad8cfddb5ea556a5644c9fde to your computer and use it in GitHub Desktop.
Save miguelmota/25568433ad8cfddb5ea556a5644c9fde 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
@wenweih
Copy link

wenweih commented Dec 14, 2020

Thanks for the sharing.

@doctorlai-msrc
Copy link

Thanks for sharing!

@abin1989
Copy link

Thanks for the sharing.

@fjod
Copy link

fjod commented Jun 22, 2023

Thank you!

@AdamDomagalsky
Copy link

AdamDomagalsky commented Aug 30, 2023

Keep in mind when comparing 2 same protos, use proto.Equal(message, newMessage) as they will differ under the hood. see: issue-1336

@Bikara950225
Copy link

Thanks for sharing!

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