gin返回protobuf,python解析protobuf
go代码
- user.proto文件
syntax = "proto3";
option go_package = "./;proto";
message Teacher {
string name = 1;
repeated string course = 2;
}
执行命令生成user.pb.go源码
protoc -I . user.proto --go_out=plugins=grpc:.
- main.go文件(通过gin框架返回protobuf格式的数据)
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"goRPC/gin_start/06_gin_return_protobuf/proto"
)
func main() {
r := gin.Default()
r.GET("/some-protobuf", returnProto)
r.Run()
}
func returnProto(context *gin.Context) {
teacher := proto.Teacher{
Name: "mayanan",
Course: []string{"python", "go", "微服务"},
}
context.ProtoBuf(http.StatusOK, &teacher)
}
运行go服务
python代码
- user.proto文件 (同go保持一致)
执行命令生成两个源码文件:user_pb2.py、user_pb2_grpc.py
python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. user.proto
- test.py文件
发起请求,解析protobuf格式的数据
import requests
from requests_test.proto import user_pb2
user = user_pb2.Teacher()
rsp = requests.get("http://127.0.0.1:8080/some-protobuf")
print(rsp.text)
user.ParseFromString(rsp.content)
print(user.name, user.course) # mayanan ['python', 'go', '微服务']