Go每日一库之102:grpcurl
grpcurl是一个命令行工具,使用它可以在命令行中访问gRPC服务,就像使用curl访问http服务一样。
准备
在gRPC服务中注册reflection服务:
gRPC服务是使用Protobuf(PB)协议的,而PB提供了在运行时获取Proto定义信息的反射功能。grpc-go中的"google.golang.org/grpc/reflection"包就对这个反射功能提供了支持。
这里以grpc-go官方的helloword为例,代码结构如下:
grpc-hello
├── go.mod
├── go.sum
├── main.go
└── proto
├── doc.go
├── helloworld.pb.go
└── helloworld.proto
helloworld.proto:
syntax = "proto3";
package proto;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
main.go:
package main
import "fmt"
import "log"
import "net"
import "context"
import "grpc-hello/proto"
import "google.golang.org/grpc"
import "google.golang.org/grpc/reflection"
func main() {
lis, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
server := grpc.NewServer()
// 注册grpcurl所需的reflection服务
reflection.Register(server)
// 注册业务服务
proto.RegisterGreeterServer(server, &greeter{})
if err := server.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
type greeter struct {
}
func (*greeter) SayHello(ctx context.Context, req *proto.HelloRequest) (*proto.HelloReply, error) {
fmt.Println(req)
reply := &proto.HelloReply{Message: "hello"}
return reply, nil
}
在main.go的第19行,使用reflection.Register(server)注册了reflection服务。
安装和使用
安装grpcurl:
go install github.com/fullstorydev/grpcurl/cmd/grpcurl
使用示例:
- 查看服务列表:
$ grpcurl -plaintext 127.0.0.1:8080 list
grpc.reflection.v1alpha.ServerReflection
proto.Greeter
- 查看某个服务的方法列表:
$ grpcurl -plaintext 127.0.0.1:8080 list proto.Greeter
proto.Greeter.SayHello
- 查看方法定义:
$ grpcurl -plaintext 127.0.0.1:8080 describe proto.Greeter.SayHello
proto.Greeter.SayHello is a method:
rpc SayHello ( .proto.HelloRequest ) returns ( .proto.HelloReply );
- 查看请求参数:
$ grpcurl -plaintext 127.0.0.1:8080 describe proto.HelloRequest
proto.HelloRequest is a message:
message HelloRequest {
string name = 1;
}
- 调用服务,参数传json即可:
$ grpcurl -d '{"name": "abc"}' -plaintext 127.0.0.1:8080 proto.Greeter.SayHello
{
"message": "hello"
}
总结
grpcurl这个工具从使用上十分简单,查看服务信息基本上类似展示的proto文件的内容,调用服务这个功能还是很实用的,可以整合到k8s的Pod镜像中,用于在k8s集群内部简单测试gRPC服务。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!