go|修复grpc 返回字段为该字段类型的默认值时,不传该字段问题

在使用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})

    推荐阅读