本仓库存存放一些本人收集的gRPC接口命令行测试工具的使用,包含以下部分
该测试工程使用go mod进行依赖管理,如果依赖包下载缓慢,可以使用下面的代理进行下载。
GOPROXY="https://goproxy.cn,direct"
GOSUMDB="off"
启动服务
go run main.go
接口声明
syntax = "proto3";
package example;
message H3Req {
string msgType = 1;
map<string, string> headers = 2;
bytes body = 3;
bool fin = 4;
}
message H3Resp {
string msgType = 1;
map<string, string> headers = 2;
bytes body = 3;
bool fin = 4;
}
// wrapper service
service H3Wrapper {
rpc Stream (stream H3Req) returns (stream H3Resp);
rpc OneWay (H3Req) returns (H3Resp);
}
本文提到的两个工具都是通过json发起调用的,json和pb之间的转化关系可以参考这里
强调一下pb中的二进制bytes对应着json中的base64字符串。
# 获取所有服务
grpcurl -plaintext 127.0.0.1:18000 list
# 获取服务的方法
grpcurl -plaintext 127.0.0.1:18000 list example.H3Wrapper
# 获取方法的声明
grpcurl -plaintext 127.0.0.1:18000 describe example.H3Wrapper.Stream
# 获取message的定义
grpcurl -plaintext 127.0.0.1:18000 describe .example.H3Req
grpcurl -plaintext -d '{"msgType":"header","headers":{"content-type":"application/json"},"fin":false}' 127.0.0.1:18000 example.H3Wrapper/OneWay
对于流式接口,grpcurl的处理逻辑是每行一个json,使用控制台输入
➜ ~ grpcurl -plaintext -d @ 127.0.0.1:18000 example.H3Wrapper/Stream
# 输入
{"msgType":"header","headers":{"content-type":"application/json"},"fin":false}
# 返回
{
"msgType": "header"
}
# 输入
{"msgType":"data","body":"Z3Vvc29uZ2NodQ==","fin":false}
# 返回
{
"msgType": "data",
"body": "c2VydmVyIHJldHVybg=="
}
# 输入
{"msgType":"finish","body":"Z3Vvc29uZ2NodQ==","fin":true}
# 返回
{
"msgType": "data",
"body": "c2VydmVyIHJldHVybg==",
"fin": true
}
ghz --insecure --call example.H3Wrapper.OneWay \
-d '{"msgType":"header","headers":{"content-type":"application/json"},"fin":false}' \
127.0.0.1:18000 -c 1 -n 1
ghz --insecure --proto "${local_directory}"/../../example/example.proto --call example.H3Wrapper.OneWay \
-d '{"msgType":"header","headers":{"content-type":"application/json"},"fin":false}' \
127.0.0.1:18000 -c 1 -n 1
ghz --insecure --call example.H3Wrapper.Stream -d '[{"msgType":"header","headers":{"content-type":"application/json"},"fin":false},{"msgType":"data","body":"Z3Vvc29uZ2NodQ==","fin":false},{"msgType":"finish","body":"Z3Vvc29uZ2NodQ==","fin":true}]' 127.0.0.1:18000 -c 1 -n 1
主要思路是遍历case文件自动发起请求
# 获取当前目录
local_directory="$(cd "$(dirname "$0")" && pwd)"
for casefile in "${local_directory}"/stream/*.dat; do
grpcurl <"${casefile}" -plaintext -d @ 127.0.0.1:18000 example.H3Wrapper/Stream
done
for casefile in "${local_directory}"/oneway/*.dat; do
grpcurl <"${casefile}" -plaintext -d @ 127.0.0.1:18000 example.H3Wrapper/OneWay
done
# 获取当前目录
local_directory="$(cd "$(dirname "$0")" && pwd)"
for casefile in "${local_directory}"/oneway/*.dat; do
ghz --insecure --call example.H3Wrapper.OneWay 127.0.0.1:18000 -c 1 -n 1 -D "${casefile}"
done
# 流式接口
for casefile in "${local_directory}"/stream/*.dat; do
ghz --insecure --call example.H3Wrapper.Stream 127.0.0.1:18000 -c 1 -n 1 -D "${casefile}"
done