go - 如何使用 Go 的类型别名让自己的模型与 protobufs 一起工作?

标签 go protocol-buffers rpc twirp

我有一些 REST API,我的模型定义为 Go 结构。

type User struct {
  FirstName string
  LastName  string
}

然后我就有了获取数据的数据库方法。

GetUserByID(id int) (*User, error)

现在我想用 https://github.com/twitchtv/twirp 替换我的 REST API .

因此我开始在 .proto 文件中定义我的模型。

message User {
  string first_name = 2;
  string last_name = 3;
}

现在我有两个 User 类型。我们称它们为nativeproto 类型。

我还在我的 .proto 文件中定义了一个服务,它将用户返回到前端。

service Users {
  rpc GetUser(Id) returns (User);
}

这会生成一个我必须填写的界面。

func (s *Server) GetUser(context.Context, id) (*User, error) {
  // i'd like to reuse my existing database methods
  u, err := db.GetUserByID(id)
  // handle error
  // do more stuff
  return u, nil
}

不幸的是,这不起作用。我的数据库返回一个 native 用户,但界面需要一个 proto 用户。

有没有简单的方法让它工作?也许使用类型别名

非常感谢!

最佳答案

解决问题的一种方法是手动进行转换。

type User struct {
    FirstName string
    LastName string
}

type protoUser struct {
    firstName string
    lastName string
}

func main() {
    u := db() // Retrieve a user from a mocked db

    fmt.Println("Before:")
    fmt.Printf("%#v\n", *u) // What db returns (*protoUser)
    fmt.Println("After:")
    fmt.Printf("%#v\n", u.AsUser()) // What conversion returns (User)
}

// Mocked db that returns pointer to protoUser
func db() *protoUser {
    pu := protoUser{"John", "Dough"}
    return &pu
}

// Conversion method (converts protoUser into a User)
func (pu *protoUser) AsUser() User {
    return User{pu.firstName, pu.lastName}
}

The key part is the AsUser method on the protoUser struct.
There we simply write our custom logic for converting a protoUser into a User type we want to be working with.

Working Example

关于go - 如何使用 Go 的类型别名让自己的模型与 protobufs 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49752685/

相关文章:

java - golang jsonrpc调用java json rpc

c - 段错误(核心已转储)

html - Hugo 不显示子目录 [File.Dir] 中的页面

protocol-buffers - 为什么 Protocol Buffers 3 中删除了必需和可选

c++ - 使用 protobuf 对象作为 std::map 中的键

java - 如何确定 protobuf 中的消息类型以便我可以使用该 type.parsefrom(byte[ ])

go - Go语言一个包的所有方法返回的错误列表

go - 将 go 接口(interface)对象转换/类型转换为具体类型

google-app-engine - 附加 slice 未按预期工作

rpc - RPC流式传输的含义和场景?