在proto消息中声明字段标签。

huangapple go评论87阅读模式
英文:

Declaring a field tag in proto message

问题

我刚刚开始使用Go编程和protobuf,并且现在需要验证结构中的数据。我找到了govalidator,它似乎完美地满足了我的需求。它可以根据字段标签验证结构体,就像这样:

type Contact struct {
    firstName string `valid:"alpha,required"`
    lastName string `valid:"alpha,required"`
    email string `valid:"email,required"`
}

jdoe := &Contact{
    firstName: "John",
    lastName: "Doe",
    email: "jdoe@mail.com",
}

ok, err = govalidator.ValidateStruct(jdoe)

而我的protobuf定义如下:

message Contact {
    string firstName = 1;
    string lastName = 2;
    string email = 3;
}

现在我的问题是,是否有办法在proto消息中定义字段标签?根据我在生成的go代码中看到的情况,编译器无论如何都会为字段添加标签,但我能否“偷偷摸摸”地添加我需要的标签呢?此外,我想到可能可以使用解组(unmarshalling)来解决问题,但对我来说,解组只是为了将字段值复制到具有必要字段标签的等效结构体中,似乎效率不高。

英文:

I just dived in Go programming using protobuf and I'm at the point where I need to validate data in a struct. I found govalidator, which seems to do the perfect job for what I need. It does validate structs based on the field tags, something like

type Contact struct {
    firstName string `valid:"alpha,required"`
    lastName string `valid:"alpha,required"`
    email string `valid:"email,required"`
}

jdoe := &Contact{
    firstName: "John",
    lastName: "Doe",
    email: "jdoe@mail.com"
}

ok, err = govalidator.ValidateStruct(jdoe)

And my protobuf definition would look like

message Contact {
    string firstName = 1;
    string lastName = 2;
    string email = 3;
}

Now my question would be, is there a way to define the field tags in the proto message. From what I've seen in the generated go code, the compiler adds tags to the fields anyway, but could I "sneak" the ones that I need too? Also, I would imagine that unmarshalling could be one possible solution, but it somehow seems inefficient to me to unmarshal just to copy the field values to an equivalent struct which would have the necessary field tags.

答案1

得分: 2

将数据封装的结构与来自客户端的输入具有相同的结构只是纯粹的巧合。正如评论中和比我更有经验的同事建议的那样,我只是将由proto生成的结构的字段(在这种特殊情况下是一对一)映射到我定义的数据封装结构中。

英文:

Having the same structure for the data encapsulation and the input coming from the client was just a pure coincidence. As it has been suggested not only in the comments, but also by co-workers more experienced (than me) with protobuf I've just mapped (1:1 in this particular case) the fields from the structure generated by proto to the data encapsulation structure I have defined.

huangapple
  • 本文由 发表于 2016年2月18日 15:41:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/35475529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定