> 文章列表 > 对restful的支持 rust-grpc-proxy

对restful的支持 rust-grpc-proxy

对restful的支持 rust-grpc-proxy

目录

  • 前言
  • 快速体验
  • 说明
    • 1. 启动目标服务
    • 2. 启动代理
    • 3. 测试
    • 4. example.sh
  • 尾语

前言

继上一篇博文的展望,这个月rust-grpc-proxy提供了对restful的简单支持。
并且提供了完成的用例,见地址如下,
https://github.com/woshihaoren4/grpc-proxy/tree/main/example/restful
下面我们来体验一下

快速体验

github 地址 https://github.com/woshihaoren4/grpc-proxy

cd example/restful
chmod +x example.sh
./example.sh

会见到如下输出,说明服务运行和测试成功,细节详见example.sh文件
对restful的支持 rust-grpc-proxy

说明

上面到底干了个啥那,让我们往下看

1. 启动目标服务

首先启动两个提供grpc服务的程序SERVICE_ECHOSERVICE_GREET,他们的proto如下

  • EchoGet 方法的路径get: "/api/v1/echo/{request}/get" ,这里{request}是声明此处的路径会被解析到方法入参EchoGetRequest
  • EchoGet 对应的是一个get请求,其中入参EchoGetRequest的另一个参数int32 query = 2;,没有在path中声明,则会在http请求中的query种解析
// Echo Service
service EchoService {rpc EchoGet(EchoGetRequest) returns (EchoGetResponse){option (google.api.http) = {get: "/api/v1/echo/{request}/get"};};rpc EchoPost(EchoGetRequest) returns (EchoGetResponse){option (google.api.http) = {post: "/api/v1/echo/post"body: "*"};};
}// Echo Service
service GreetService {rpc GreetGet(GreetGetRequest) returns (GreetGetResponse){option (google.api.http) = {get: "/api/v1/greet/{request}"};};
}message EchoGetRequest {string request = 1;int32 query = 2;
}message EchoGetResponse {string response = 1;
}message GreetGetRequest {string request = 1;string content = 2;
}message GreetGetResponse {string response = 1;
}

2. 启动代理

启动代理钱会先生成测试文件,这里指明了我们上面启动的两个服务的地址 和路径前缀,配置文件如下

[[proxy_sink]]
name = "echo"
addr = "127.0.0.1:1234"
prefix = "/api/v1/echo"[[proxy_sink]]
name = "hello"
addr = "127.0.0.1:1235"
prefix = "/api/v1/greet"

生成文件后就会启动代理

3. 测试

代理启动后会执行三个curl,根据返回的结果断言 验证服务的正确性
比如测试用例一

function test_one() {result=$(curl -s -l --location --request GET 'http://127.0.0.1:6789/api/v1/echo/hello/get?query=666' | jq -r '."response"')assert_eq "$result" 'GET [SERVICE_ECHO]---> request=hello query=666' "test_one"
}

4. example.sh

不带任何参数执行example.sh,会自动生成目标服务,配置文件,代理服务,并自行验证。
这些生成好的服务和配置并不会自行销毁,再次执行脚本时,若存在则跳过,不存在则生成

可使用如下参数清理

  • clean 清理代理服务,目标服务,配置文件
  • config 重置配置文件

尾语

我在工作中尝试了rust-grpc-proxy,目前很受测试同学的期待,因为我们采用微服务架构,很多服务都只提供了grpc接口,这让测试同学很抓狂,
一是grpc测试非常费劲,又用protobuf编码,通讯内容不易阅读,调试也很费劲。不光测试,安全部门也会各种扫描业务服务,同样头疼grpc的安全性测试。每次proto的变动都需要各方重新编码,效率极低。
二是我们的自动化测试平台对grpc支持并不友好,或者说所有的自动化测试平台对grpc支持都很有限。如果用rust-grpc-proxy将grpc和http格式转换,就能为自动化测试提供极大便利。