簡體   English   中英

如何使用協議緩沖區序列化Go結構並在Dart over Ajax中使用它們

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

如果我的服務器上的sql數據庫中有大量的類型化數據,那么如何使用協議緩沖區將此數據發送到dart客戶端?

首先在計算機上安裝protoc

sudo apt-get install protobuf-compiler

然后從https://code.google.com/p/goprotobuf/安裝go協議緩沖區庫。 dartlang版本可以在這里找到: https//github.com/dart-lang/dart-protoc-plugin

下一步是編寫一個.proto文件,其中包含要發送的消息的定義。 可以在此處找到示例: https//developers.google.com/protocol-buffers/docs/proto

例如:

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

然后使用protoc工具為此proto文件編譯go文件和dart文件。

要在go中創建Car對象,請記住使用提供的類型:

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

然后你可以通過http.ResponseWriter發送對象,如下所示:

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

在Dart代碼中,您可以按如下方式獲取信息:

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);
    });
}

如果一切正常,你現在應該在你的Dart應用程序中有一個Car對象:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM