Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k 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 Reply

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
  // 请问要如何解决呢?
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...