修復grpc 返回欄位為該欄位型別的預設值時,不傳該欄位問題
阿新 • • 發佈:2019-02-09
在使用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 }
grpc-gateway
package main import ( "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})