创建一个proto文件
- 指定proto版本为proto3, 目前主流使用的都是proto3
syntax = "proto3";
option go_package="./goproto;goproto";
message HelloRequest {
string name = 1;
}
message HelloResponse {
string reply = 1;
}
service HelloService{
rpc Hello(HelloRequest) returns (HelloResponse);
}
生成go stub
- 使用go-grpc 插件会帮我自动生成客户端stub和服务端stub
protoc --go_out=. helloword.proto
protoc --go_out=. --go-grpc_out=. helloword.proto
比较protobuf和json序列化后的长度
func main() {
h := &goproto.HelloRequest{
Name: "boy",
}
pbMarshal, _ := proto.Marshal(h)
fmt.Println(len(pbMarshal))
jsonMarshal, _ := json.Marshal(h)
fmt.Println(len(jsonMarshal))
}