questions icon indicating copy to clipboard operation
questions copied to clipboard

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

Open aredcup opened this issue 5 years ago • 1 comments

使用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 int32 protobuf:"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 []byte json:"-"XXX_sizecache int32 json:"-" } 手动删除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, } 我应该如何设置才能返回空字段为默认类型

aredcup avatar Apr 30 '20 03:04 aredcup

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

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

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

printfcoder avatar Apr 30 '20 04:04 printfcoder