在使用go 的grpc通信时,会有一个坑,当grpc 返回字段为该字段类型的默认值时,为了节省带宽,不会传输该字段,这对客户端来说,数据结构不严谨,解决办法
grpc :
import (
pb "github.com/golang/protobuf/jsonpb"
)func marshalJsonp(pbMsg proto.Message) (msg []byte, err error) {
m := pb.Marshaler{EmitDefaults: true, OrigName: true}
var data bytes.Buffer
err = m.Marshal(&data, pbMsg)
return data.Bytes(), err
}
【go|修复grpc 返回字段为该字段类型的默认值时,不传该字段问题】grpc-gateway
package mainimport (
"flag"
"net/http""github.com/golang/glog"
"golang.org/x/net/context"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golang.org/grpc"
gw "path/to/your_service_package"
)var (
echoEndpoint = flag.String("echo_endpoint", "localhost:9090", "endpoint of YourService")
)func run() error {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true})
opts := []grpc.DialOption{grpc.WithInsecure()}
err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts)
if err != nil {
return err
}return http.ListenAndServe(":8080", mux)
}func main() {
flag.Parse()
defer glog.Flush()if err := run();
err != nil {
glog.Fatal(err)
}
}
起作用的就是下面这句配置:
mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName: true, EmitDefaults: true})
推荐阅读
- Go|Docker后端部署详解(Go+Nginx)
- GO|GO,GO,GO!
- Go成长之路|go中判断空字符串、nil和len(t)的用法
- grpc- python调用c++的rpc服务
- cmake|cmake - 如何生成grpc的*.pb.cc和*.pb.h文件
- go编译tools
- GRPC 负载均衡实现
- AspNetCore|gRPC-Web 踩坑记
- go grpc安装与使用