stack-labs / questions

任何关于Micro的问题都可以在Issue中创建
27 stars 6 forks source link

关于用grpc协议不返回空字段问题 #61

Open aredcup opened 4 years ago

aredcup commented 4 years ago

使用go-micro版本号:v2.5.0 micro的版本号:v2.5.0 micro api设置: MICRO_API_ENABLE_RPC=true proto文件: type AdminListResponse struct { //@inject_tag: json:"count" // google.protobuf.Int32Value count = 1 ; Count int32protobuf:"varint,1,name=count,proto3" json:"count" //用户信息 //@inject_tag: json:"accounts" Accounts []*AdminInfoprotobuf:"bytes,2,rep,name=accounts,proto3" json:"accounts" XXX_NoUnkeyedLiteral struct{}json:"-" XXX_unrecognized []bytejson:"-" XXX_sizecache int32json:"-" } 手动删除omitempty后空字段还是不返回默认值

handler : `func (h Admin) List(ctx context.Context, req accountpb.AdminListRequest, rsp *accountpb.AdminListResponse) error { var ( //err error count int32 ) //if rsp.Accounts, count, err = h.accountCore.AdminList(req.GetPage(), req.GetLimit(), req.GetSort(), req.GetWhere()); err != nil { // return err //}

//rsp.Count = &wrappers.Int32Value{Value: count}
rsp.Count = count

return nil

}`

看源码:go-micro/v2/server/grpc中jsonpb默认设置不返回字段 var jsonpbMarshaler = &jsonpb.Marshaler{ EnumsAsInts: false, EmitDefaults: false, OrigName: true, } 我应该如何设置才能返回空字段为默认类型

printfcoder commented 4 years ago

可以使用grpc.Codec方法将默认的编码器覆盖掉Server中的对应格式的Codec,比如:

srv.Server().Init(serverGRPC.Codec("application/json", &jsonCodec{}))

见:https://github.com/micro-in-cn/tutorials/tree/master/examples/grpc/codec