简体   繁体   English

Protobuf,Go和私有字段

[英]Protobuf, Go and private fields

Let's say I've got a Player defined in my .proto file. 假设我在.proto文件中定义了一个Player

message Player {
  string first_name = 1;
  string last_name = 2;
  int32 user_id = 3;
}

I'm using https://github.com/twitchtv/twirp to communicate between my Go backend and my JavaScript frontend. 我正在使用https://github.com/twitchtv/twirp在Go后端和JavaScript前端之间进行通信。 If you don't know Twirp it's simply JSON RPC over HTTP 1.1. 如果您不了解Twirp,那只是HTTP 1.1上的JSON RPC。

The Player message is converted into a Go struct Player消息将转换为Go结构

type Player struct {
  FirstName string
  LastName string
  UserId int32
}

As we all know uppercase fields are public. 众所周知,大写字段是公共的。 However I'd like to keep the UserId private, ie make it lowercase. 但是,我想将UserId保持私有,即使其小写。 My users in the frontend should not be able to see the UserId of a player. 我在前端的用户应该看不到播放器的UserId In my backend I need this information so I cannot simply remove the field. 在我的后端,我需要此信息,所以我不能简单地删除该字段。

Any ideas how to handle such a situation? 任何想法如何处理这种情况? Is it possible to have private fields in my .proto files? .proto文件中是否可以包含私有字段?

Protobuf is for communication , not for database modeling. Protobuf用于通信 ,而不用于数据库建模。 You should use protobuf to describe the data structures you intend to send over / receive from your clients. 您应该使用protobuf来描述您打算通过客户端发送/接收的数据结构。

If you don't intend to send the user ID to the clients, don't include that in your protobuf Player definition. 如果您不打算将用户ID发送给客户端,则不要在protobuf Player定义中包括该ID。

The Player you send to the clients and the Player you store in your database does not have to be the same. Player发送到客户端和Player您在数据库中存储不必是相同的。 More often they are not the same, you usually store other fields such as creation time, database ID etc. which are not for the clients. 通常,它们不相同,您通常存储不适用于客户端的其他字段,例如创建时间,数据库ID等。

So you should have 2 separate structures for a Player , one that the server uses (stores), and one that clients see. 因此,对于Player ,您应该具有2个单独的结构,服务器使用(存储)一个结构,客户端可以看到一个结构。 Of course when defining those 2 structs, you may utilize one in the other to prevent repetition, eg the server player may embed the client player, eg: 当然,在定义这两个结构时,可以在另一个结构中加以利用以防止重复,例如服务器播放器可以嵌入客户端播放器,例如:

New proto Player : 新的原型Player

message Player {
  string first_name = 1;
  string last_name = 2;
}

Client Player : 客户Player

type Player struct {
    FirstName string
    LastName string
}

Server Player : 服务器Player

type DBPlayer struct {
    Player // Embed Player

    UserId int32
}

And when you load a DBPlayer in your server, you would only send the DBPlayer.Player field to the client, the rest is "private". 并且,当您在服务器中加载DBPlayer时,您只会将DBPlayer.Player字段发送给客户端,其余为“私有”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM