GRPC調試工具

grpcurlgrpcui 都是調試grpc的利器,前者用於命令行,相似curl工具;後者是以web的形式進行調試的,相似postman工具。git

有了這兩款工具,咱們不用寫任何客戶端代碼,也能方便的調試接口數據。github

這兩款工具的做者是同一人:http://github.com/fullstorydevgolang

grpcurl

根據官方 README.md 文檔安裝便可。web

export GOPROXY=https://mirrors.aliyun.com/goproxy/
go get github.com/fullstorydev/grpcurl
go install github.com/fullstorydev/grpcurl/cmd/grpcurl

這時,在 $GOPATH/bin 目錄下,生成一個 grpcurl 可執行文件。咱們能夠複製到 /usr/local/bin/ 下:瀏覽器

# mac
sudo cp `go env|grep 'GOPATH'|sed -e 's/GOPATH="//' -e 's/"//'`/bin/grpcurl /usr/local/bin/
chmod +x /usr/local/bin/grpcurl

執行個命令,驗證下:bash

$ grpcurl -version

grpcurl 1.3.2

輸出了版本號表示安裝成功了。curl

示例

下面這個GetMobileArea方法能夠返回手機歸屬地信息,其中GRPC服務端地址:127.0.0.1:8105。咱們測試一下:ide

$ grpcurl -plaintext -d '{"PhoneNum":"13523456666"}' 127.0.0.1:8105 Ys.Pb.ChituSms.ChituSmsServ/GetMobileArea

{
  "status": {
    "logid": "1233268494511693824"
  },
  "data": {
    "PhoneNum": "13523456666",
    "Province": "河南",
    "City": "鄭州",
    "ZipCode": "450000",
    "AreaZone": "0371",
    "CardType": "中國移動"
  }
}

-d表示傳參,Ys.Pb.ChituSms.ChituSmsServ/GetMobileArea分別表示命名空間+service名稱+方法名工具

若是提示:post

Failed to compute set of methods to expose: server does not support the reflection API

這種狀況下,加個反射就能夠了,在 main.go 新增以下代碼便可:

//註冊反射
reflection.Register(s)

再運行一次就好了。

grpcui

安裝方法和grpcurl同樣:

export GOPROXY=https://mirrors.aliyun.com/goproxy/
go get github.com/fullstorydev/grpcui
go install github.com/fullstorydev/grpcui/cmd/grpcui

# mac
sudo cp `go env|grep 'GOPATH'|sed -e 's/GOPATH="//' -e 's/"//'`/bin/grpcui /usr/local/bin/
chmod +x /usr/local/bin/grpcui
$ grpcui -version

grpcui dev build <no version set>

示例

下面以一個測試的grpc項目爲例,假設業務端口號:8105。一樣須要在 main.go 新增以下代碼:

//註冊反射
reflection.Register(s)

而後命令行運行工具:

$ grpcui -plaintext 127.0.0.1:8105

gRPC Web UI available at http://127.0.0.1:55984/

在瀏覽器中訪問:http://127.0.0.1:55984/

到這,咱們看到 Service name、Method name 都出來了,傳輸參數直接在頁面上進行操做便可。

參考資料

一、Go gRPC 調試工具
https://studygolang.com/articles/24551?fr=sidebar
二、fullstorydev/grpcui: An interactive web UI for gRPC, along the lines of postman
https://github.com/fullstorydev/grpcui

相關文章
相關標籤/搜索