Marshal/Unmarshal Protocol Buffers in Go: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
(Created page with "=Internal= * Protocol Buffer Concepts")
 
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
=Internal=
=Internal=
* [[Protocol_Buffer_Concepts#Protocol_Buffer_Go_Code_Examples|Protocol Buffer Concepts]]
* [[Protocol_Buffer_Concepts#Protocol_Buffer_Go_Code_Examples|Protocol Buffer Concepts]]
=Overview=
This example uses this message definition:
<syntaxhighlight lang='protobuf'>
message SomeMessage {
  int32 id = 1;
  bool  is_valid = 2;
  string name = 3;
  repeated string sample_list = 4;
}
</syntaxhighlight>
The Go code is generated following the instructions from: {{Internal|Protocol_Buffers_Data_Type_Go_Code_Generation#Overview|Protocol Buffers Go Code Generation}}
=Marshaling and Unmarshaling=
<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>

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:

Protocol Buffers Go Code Generation

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 { ... }