Go gRPC 调试工具 -grpcui
概述
gRPC 接口调试工具:grpcui(https://github.com/fullstorydev/grpcui)
grpcui is a command-line tool that lets you interact with gRPC servers via a browser. It’s sort of like Postman, but for gRPC APIs instead of REST.
安装
go get github.com/fullstorydev/grpcui
go install github.com/fullstorydev/grpcui/cmd/grpcui
验证安装是否成功
grpcui -help
安装成功
Usage:
D:\xxxxx\bin\grpcui.exe [flags] [address]
Starts a web server that hosts a web UI for sending RPCs to the given address.
The address will typically be in the form "host:port" where host can be an IP
address or a hostname and port is a numeric port or service name. If an IPv6
address is given, it must be surrounded by brackets, like "[2001:db8::1]". For
Unix variants, if a -unix=true flag is present, then the address must be the
path to the domain socket.
Most flags control how the connection to the gRPC server is established. The
web server will always bind only to localhost, without TLS, so only the port
can be controlled via command-line flags.
Demo
定义proto
//版本号
syntax="proto3";
//指定生成user.pb.go的包名
package proto;
//定义客户端请求的数据格式
message UserRequest{
string name =1;
}
//定义服务端请求的数据格式
message UserResponse{
int32 id=1;
string name=2;
int32 age=3;
repeated string hobby=4;
}
//定义服务端响应的数据格式
service UserInfoService{
rpc GetUserInfo(UserRequest)returns (UserResponse){}
}
实现这个接口类
//定义服务端约定的接口
type UserInfoService struct {
}
var us UserInfoService
func (u *UserInfoService) GetUserInfo(ctx context.Context, req *proto.UserRequest) (resp *proto.UserResponse, err error) {
name := req.Name
//从数据库查找数据 这边模拟数据库的查找
if name == "zs" {
return &proto.UserResponse{
Id: 1,
Name: "zs",
Age: 18,
Hobby: []string{"cook", "code", "run"},
}, nil
}
return nil, nil
}
func main() {
//1.监听
listen, err := net.Listen("tcp", "127.0.0.1:8000")
if err != nil {
log.Fatal("net.listen failed err:", err)
}
log.Println("127.0.0.1:8000 has listening")
//2.实例化grpc服务端
serv := grpc.NewServer()
//3.在gRPC中注册该服务
//第二个参数要接口类型的变量
proto.RegisterUserInfoServiceServer(serv, &us)
//不加该映射 执行grpcui -plaintext 127.0.0.1:8000打开grpcui会报错
reflection.Register(serv)
//4.启动gRPC服务端
serv.Serve(listen)
}
运行服务
grpcui -plaintext 127.0.0.1:8000
#注意;需要给服务加个反射才可以运行
reflection.Register(serv)
#要不然会报错:Failed to compute set of methods to expose: server does not support the reflection API
访问web UI 的url