grpcurl 调试 gRPC 接口
更新时间:2026-09-18。gRPC 是二进制 HTTP/2 + Protobuf,普通 curl 没法直接调。
grpcurl就是「gRPC 版 curl」。协议背景见 gRPC 性能:keepalive 与多路复用,压测见 ghz。
这个工具是做什么的
grpcurl 在命令行列出服务、查看方法签名和消息结构、发送 JSON 请求(内部按 proto 转成 protobuf),并把响应用 JSON 打印。依赖服务端开启 gRPC Server Reflection,或本地提供 .proto。
一、列出服务与方法(依赖反射)
bash
# 明文(本地/未上 TLS 必须加 -plaintext,否则握手失败)
grpcurl -plaintext localhost:9090 list
# grpc.health.v1.Health
# user.UserService
grpcurl -plaintext localhost:9090 list user.UserService
# CreateUser
# GetUser
grpcurl -plaintext localhost:9090 describe user.UserService.GetUser
# rpc GetUser ( .user.GetUserRequest ) returns ( .user.GetUserResponse );
grpcurl -plaintext localhost:9090 describe user.GetUserRequest
# 打印字段名、类型、嵌套结构二、发起调用
bash
# 一元调用,-d 传 JSON(字段名用 proto 里的 camelCase 或 snake_case 均可)
grpcurl -plaintext -d '{"id": 123}' \
localhost:9090 user.UserService/GetUser
# 带 metadata(header),多个 -H
grpcurl -plaintext -H 'authorization: Bearer xxx' -H 'x-tenant: t1' \
-d '{"id":1}' localhost:9090 user.UserService/GetUser
# TLS(默认校验证书);自签用 -insecure
grpcurl -d '{"id":1}' api.example.com:443 user.UserService/GetUser三、服务端没开 reflection
用本地 proto 描述,grpcurl 自行编译:
bash
grpcurl -plaintext \
-import-path ./proto -proto user.proto \
-d '{"id":1}' localhost:9090 user.UserService/GetUser
# 多个 proto 有依赖时,-import-path 指向根目录,再 -proto 给入口文件生产常关闭 reflection(避免暴露方法清单),这时就走 -proto 方式。
四、流式与健康检查
bash
# 服务端流 / 双向流:-d 给多行 JSON(每行一条消息)
# 客户端流可配合 -d @ 从 stdin 读
( echo '{"id":1}'; echo '{"id":2}' ) | \
grpcurl -plaintext -d @ localhost:9090 user.UserService/StreamUsers
# 标准健康检查协议
grpcurl -plaintext localhost:9090 grpc.health.v1.Health/Check常见坑
- 忘
-plaintext:连本地 h2c 端口直接 TLS 握手报错,本地调试基本都要带。 - 生产没开 reflection:
list报 "server does not support reflection",改用-import-path/-proto。 - JSON 字段类型/枚举:枚举既可用字符串名也可用数字;
int64在 JSON 里是字符串(防精度丢失),别写成数字导致解析失败。 - TLS 自签:加
-insecure跳过校验(仅测试环境)。 - 方法全名格式:是
包.服务/方法(斜杠分隔方法),写错会得到 NotFound。 - 超时默认较长:排障时加
-max-time 5避免卡死。
总结
grpcurl 是面向 gRPC/Protobuf 的 curl:先用 -plaintext 加 list/describe 借助服务端反射枚举服务、方法和消息结构,再用 -d 传 JSON 调用 包.服务/方法(内部自动转 protobuf),用 -H 传 metadata、-insecure 处理自签 TLS;当生产关闭 reflection 时改用 -import-path 指向 proto 根目录加 -proto 指定文件,流式调用用 -d @ 从 stdin 喂多行 JSON,还能直接调 grpc.health.v1.Health 做健康检查;最常见错误是本地连 h2c 忘加 -plaintext、int64 要以字符串传、以及方法名必须是“包.服务/方法”格式,压测则换用 ghz。