-
-
Save michaeljs1990/114d6573b9d7cedd4f2f001894026987 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment