Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
990 views
in Technique[技术] by (71.8m points)

grpc 如何将model数据转换为proto生成的结构体返回?

刚开始学习grpc 遇到问题请教下

model:

type User struct {
 Id       int64 `json:"id"`
 Nickname string `json:"nickname"`
}

func  Users()[]*User {
   var rows []*User
   db.Find(&rows)
   return rows
}

proto

type User struct {
 Id                   int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
 Nickname             string `protobuf:"bytes,2,opt,name=nickname,proto3" json:"nickname,omitempty"`
 XXX_NoUnkeyedLiteral struct{} `json:"-"`
 XXX_unrecognized     []byte `json:"-"`
 XXX_sizecache        int32 `json:"-"`
}

response

type UserResponse struct {
   Message              string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
 Data                 []*User `protobuf:"bytes,2,rep,name=data,proto3" json:"data,omitempty"`
 XXX_NoUnkeyedLiteral struct{}      `json:"-"`
 XXX_unrecognized     []byte `json:"-"`
 XXX_sizecache        int32 `json:"-"`
}

userServer

func (c *userServer) Users(ctx context.Context, request *pb.UserRequest, response *pb.UserResponse) error {
  users := model.Users()
  
  // 这里要将[]*model.User 返回 但是pb生成的是[]*pb.User
  // 请问要如何解决呢?
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
func (c *userServer) Users(ctx context.Context, request *pb.UserRequest, response *pb.UserResponse) error {
  users := model.Users()
  for _,u := range users {
    pb.Data = append(pb.Data, &pb.User{Id:u.Id,Nickname:u.Nickname})
  }
  // 这里要将[]*model.User 返回 但是pb生成的是[]*pb.User
  // 请问要如何解决呢?
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...