Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize Go structures using protocol buffers and use them in Dart over Ajax

If you have a large amount of typed data in an sql database on my server, how do you send this data to a dart client using protocol buffers?

like image 309
ehrt1974 Avatar asked Sep 26 '13 18:09

ehrt1974


People also ask

Can Protobuf be used without gRPC?

You can use protobuf inside any program, that has no need to be client/server. If you need to exchange data, and want them to be strongly typed, protobuf is a nice option (fast & reliable).

What is Protobuf serialization?

Protocol Buffers (Protobuf) is a free and open-source cross-platform data format used to serialize structured data. It is useful in developing programs to communicate with each other over a network or for storing data.

What is Gogo Protobuf?

For those who are not aware of it, Gogo ProtoBuf is a fork of the original ProtoBuf APIv1 that includes a custom code generator with optional support for many performance related features.


1 Answers

First install protoc on your computer using

sudo apt-get install protobuf-compiler

Then install the go protocol buffer library from https://code.google.com/p/goprotobuf/. The dartlang version can be found here: https://github.com/dart-lang/dart-protoc-plugin.

The next step is to write a .proto file containing a definition of the message to be sent. examples can be found here: https://developers.google.com/protocol-buffers/docs/proto.

For example:

message Car {
    required string make = 1;
    required int32 numdoors = 2;
}

Then use the protoc tool to compile a go file and a dart file for this proto file.

To create a Car object in go, remember to use the types provided:

c := new(Car)
c.Make = proto.String("Citroën")
c.Numdoors = proto.Int32(4)

Then you can send the object over an http.ResponseWriter, w as follows:

binaryData, err := proto.Marshal(c)
if err != nil {
  // do something with error
}
w.Write(binaryData)

In the Dart code, you can fetch the information as follows:

void getProtoBuffer() {
    HttpRequest.request("http://my.url.com", responseType: "arraybuffer").then( (request) {
        Uint8List buffer = new Uint8List.view(request.response, 0, (request.response as ByteBuffer).lengthInBytes); // this is a hack for dart2js because of a bug
        Car c = new Car.fromBuffer(buffer);
        print(c);
    });
}

If everything worked, you should now have a Car object in your Dart application :)

like image 77
ehrt1974 Avatar answered Sep 23 '22 14:09

ehrt1974