Marshal/Unmarshal Protocol Buffers in Go
Jump to navigation
Jump to search
Internal
Overview
This example uses this message definition:
message SomeMessage {
int32 id = 1;
bool is_valid = 2;
string name = 3;
repeated string sample_list = 4;
}
The Go code is generated following the instructions from:
Marshaling and Unmarshaling
import (
"fmt"
"os"
"example.com/blue/pkg/somepkgpb"
"github.com/golang/protobuf/proto"
)
sm := &somepkgpb.SomeMessage{
Id: 1,
IsValid: true,
Name: "something",
SampleList: []string{"a", "b", "c"},
}
ba, err := proto.Marshal(sm)
if err != nil { ... }
err = os.WriteFile("somefile", ba, 0644)
if err != nil { ... }
ba2, err := os.ReadFile(fileName)
if err != nil { ... }
sm2 := &somepkgpb.SomeMessage{}
err = proto.Unmarshal(ba2, sm2)
if err != nil { ... }