默认为Dart-RPC在服务器和客户端之间传输对象(类实例)时使用 JSON 序列化。
如何使用Protobuf (Protocol Buffers)而是序列化?
是否可以使用 Accept
请求 header 指定序列化方法(如内容类型)?
这是我尝试过的,
我使用了以下表示 Person
实体的 .proto
定义文件:
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
它使用 protoc-gen-dart plugin 为我生成了 person.pb.dart
,通过运行命令:
protoc person.proto --dart_out=. --plugin ./protoc-gen-dart
以及一些样板 dart-rpc 代码:
import 'dart:io';
import 'package:rpc/rpc.dart';
import 'person.pb.dart';
const String _API_PREFIX = '/api';
final ApiServer _apiServer =
new ApiServer(apiPrefix: _API_PREFIX, prettyPrint: true);
main() async {
_apiServer.addApi(new Cloud());
_apiServer.enableDiscoveryApi();
HttpServer server = await HttpServer.bind(InternetAddress.ANY_IP_V4, 8080);
server.listen(_apiServer.httpRequestHandler);
}
@ApiClass(version: 'v1')
class Cloud {
@ApiMethod(method: 'GET', path: 'resource/{name}')
Person getResource(String name) {
Person p = new Person()
..id = 1
..name = name
..email = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e4f6e4f004f" rel="noreferrer noopener nofollow">[email protected]</a>';
return p; // ??? p.writeToBuffer(); ???
}
}
更新
最佳答案
rpc
仅支持 JSON。您可以在 GitHub 存储库中创建功能请求。
关于json - Dart-RPC:使用 Protocol Buffers 序列化而不是 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32175131/