在proto消息中声明一个字段标签 [英] Declaring a field tag in proto message

查看:481
本文介绍了在proto消息中声明一个字段标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在使用protobuf进行Go编程时遇到了问题,而且我正需要验证结构中的数据。我找到了 govalidator ,这似乎为我所需要的完成了工作。它确实基于字段标签验证结构,类似于

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)

我的protobuf定义看起来像

And my protobuf definition would look like

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

现在我的问题是,有没有一种方法来定义字段标签原始消息。从我在生成的go代码中看到的东西,编译器无论如何都会将标签添加到字段中,但是我能够偷偷找到我需要的代码吗?另外,我会想象unmarshalling可能是一种可能的解决方案,但对于我来说,将字段值复制到具有必要字段标签的等效结构中,似乎效率不高。

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.

推荐答案

这篇关于在proto消息中声明一个字段标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆