Skip to content

Protobufs

Gerasimos (Makis) Maropoulos edited this page Dec 10, 2019 · 3 revisions

Let's not waste time here, if you've already read the Encoding section, we can start right away.

Install protocol buffers

Install the protocol-buffers generator by downloading a github release of it and add it to your $PATH env variable, you can find the releases at this github page.

Details about protocol-buffers for Go can be found at evelopers.google.com/protocol-buffers/docs/gotutorial.

Define the data structure with protobuf

Let's start by defining what structure looks like.

Create a new file on your package named user_message.proto and fill it.

syntax="proto3";

package main;

message UserMessage {
    string Username =1;
    string Text = 2;
}

Generate proto for Go

Protobufs requires code generation.

Start a session terminal and execute:

$ protoc --go_out=. user_message.proto

This will create a user_message.pb.go which extends the data structure in protobuf form for Go.

Javascript support

Proto Marshal and Unmarshal

userMsg := &UserMessage{
    Username: "my username",
    Text: "text from terminal",
}

// send data to the "chat" event.
body, err := proto.Marshal(userMsg)
if err != nil {
    // [handle err...]
}
c.EmitBinary("chat", body)
// assuming that we are on the other side's "chat" event's callback,
// here is how you can read protobuf data.
var userMsg UserMessage
if err := proto.Unmarshal(msg.Body, &userMsg); err != nil {
    return err
}

// userMsg.Username == "my username"
// userMsg.Text == "text from terminal"

Read the complete source code by navigating to the repository's _examples/protobuf directory.