Last active
January 3, 2025 00:11
-
-
Save miguelmota/25568433ad8cfddb5ea556a5644c9fde to your computer and use it in GitHub Desktop.
Golang protobuf marshal and unmarshal example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
syntax = "proto3"; | |
message Message { | |
bytes text = 1; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protoc --go_out=example example.proto |
Thanks for sharing!
Thanks for the sharing.
Thank you!
Keep in mind when comparing 2 same protos, use proto.Equal(message, newMessage)
as they will differ under the hood. see: issue-1336
Thanks for sharing!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the sharing.