Marshal/Unmarshal Protocol Buffers in Go: Difference between revisions
Jump to navigation
Jump to search
Line 17: | Line 17: | ||
=Marshaling and Unmarshaling= | =Marshaling and Unmarshaling= | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
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 { ... } | |||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 22:42, 8 May 2024
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 { ... }