go-zero是一个设计良好的微服务框架
为什么好?
这玩意,各花入各眼,村夫觉得好,您可能觉得并不好,或至少是在您的标准中,不够好。
因此,到底为什么好,村夫不去评说。
如果您觉得go-zero不好,也不打算未来使用go-zero的,那么后面的内容,您不会遇到。直接出门右拐,也是可以的,当然如果您觉得村夫的文章可以偶尔用来打发一下厕所中的时光,也欢迎拿本文当屁股纸使使!
如果您像村夫一样,觉得go-zero是比较好用的框架,那么接下来的内容,您也有可能会遇到。欢迎您继续读下去!
问题描述
我们在设计微服务时,可能需要一个接口中返回同一个类型的数据若干条。比如:一个用户可能有多条订单。因此,我们需要在order.proto中使用如下repeated指示字描述订单信息。
message GetListReq {
string Account = 1;
}
message GetListResp {
int64 Code = 1;
repeated OrderList Data = 2;
optional string Msg = 3;
}
OrderList是我们自己定义的结构体,GetList(GetListReq)可能返回任意条订单信息,可能是0条,也可能是1条, 又或者多条。 对应生成的Go语言代码order.pb.go中,GetListResp如下:
type GetListResp struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Code int64 `protobuf:"varint,1,opt,name=Code,proto3" json:"Code,omitempty"`
Data []*OrderList `protobuf:"bytes,2,rep,name=Data,proto3" json:"Data,omitempty"`
Msg *string `protobuf:"bytes,3,opt,name=Msg,proto3,oneof" json:"Msg,omitempty"`
}
从中,我们发现Data的类型为[]*OrderList。
而在order.api中,我们可能会这样定义:
GetListReq {
Account string `json:"account"`
UserType int64 `json:"user_type"`
OrderType int64 `json:"order_type"`
}
GetListResp { //订单列表返回
Code int64 `json:"code"`
Data []OrderList `json:"data"`
Msg string `json:"msg"`
}
生成的types.go如下:
type GetListReq struct {
Account string `json:"account"` //查询者帐号:EB帐号-客户,OA号-员工
UserType int64 `json:"user_type"` // 查询者类型:201-客户,1-高层,100-员工
OrderType int64 `json:"order_type"` // 要查询的订单类型:
}
type GetListResp struct {
Code int64 `json:"code"` //接口执行情况
Data []OrderList `json:"data, optional"` // 客户的订单数据,接口成功时返回
Msg string `json:"msg, optional"` // 消息,接口失败时返回
}
Data的数据类型为[]OrderList。
这就导致我们在做数据从rpc到api传递时,需要从指针数组中向数组中值。
村夫的思路
村夫的思路如下:
res, err := l.svcCtx.OrderRpc.GetList(l.ctx, &orderclient.GetListReq{
Account: req.Account,
})
var o []order.OrderList
for _, row := range res.GetData() {
o = append(o, *row)
}
return &types.GetListResp{
Code: res.GetCode(),
Data: o,
Msg: res.GetMsg(),
}, nil
即将要返回的res.GetData()中每一个元素所指的值通过切片操作方法append追加到o数组中。
结语
毕竟村夫正经使用Golang干项目也才不到两周,几乎是个素人村夫,因此这个方法可能不是一个好方法。欢迎留言交流!
如果您觉得村夫的文章对您有所帮助,欢迎转载,同时感谢您点赞打赏!打赏的都是大哥!