验证未标记的Go结构的最佳方法是什么?

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

What's the best way to validate an untagged Go struct

问题

每当我创建一个Go结构体时,我都会使用结构标签,以便可以使用go-playground/validator轻松验证它-例如:

type DbBackedUser struct {
    Name sql.NullString `validate:"required"`
    Age  sql.NullInt64  `validate:"required"`
}

我目前正在与第三方集成。他们提供了一个Go SDK,但是SDK中的结构体不包含validate标签,并且他们无法或不愿意添加这些标签。

由于我们团队的数据完整性要求,我们必须在使用通过这个第三方SDK获取的所有数据之前对其进行验证。

问题是,在不在结构体上定义验证标签的情况下,似乎没有办法使用Validator包来验证结构体。

我们目前提出的解决方案是将SDK结构体中的所有数据映射到我们自己的结构体中(这些结构体上定义了验证标签),对这些结构体进行验证,然后,如果验证通过,我们可以直接使用SDK结构体中的数据(我们需要使用SDK定义的结构体在系统中传递数据-因此这些带有验证标签的结构体只能用于验证)。问题在于,我们将不得不维护这些仅用于验证的结构体,而且结构体之间的映射既需要时间成本又需要内存成本。

在这种情况下,有更好的处理结构体验证的方法吗?

英文:

Whenever I create a Go struct, I use struct tags so that I can easily validate it using go-playground/validator - for example:

type DbBackedUser struct {
	Name sql.NullString `validate:"required"`
	Age  sql.NullInt64  `validate:"required"`
}

I'm currently integrating with a third party. They provide a Go SDK, but the structs in the SDK don't contain validate tags, and they are unable/unwilling to add them.

Because of my team's data integrity requirements, all of the data pulled in through this third-party SDK has to be validated before we can use it.

The problem is that there doesn't seem to be a way to validate a struct using the Validator package without defining validation tags on the struct.

Our current proposed solution is to map all of the data from the SDK's structs into our own structs (with validation tags defined on them), perform the validation on these structs, and then, if that validation passes, we can use the data directly from the SDK's structs (we need to pass the data around our system using the structs defined by the SDK - so these structs with the validation tags could only be used for validation). The problem here is that we would then have to maintain these structs that are only used for validation, also, the mapping between structs has both time and memory costs.

Is there a better way of handling struct validation in this scenario?

答案1

得分: 2

替代的技术是使用验证构造函数:NewFoobar(raw []byte) (Foobar, error)

但是我看到go-validator支持你的情况,使用了“结构级验证”:

https://github.com/go-playground/validator/blob/master/_examples/struct-level/main.go

英文:

Alternative technique is to use validating constructors: NewFoobar(raw []byte) (Foobar, error)

But I see that go-validator supports your case with a "struct-level validation":

https://github.com/go-playground/validator/blob/master/_examples/struct-level/main.go

huangapple
  • 本文由 发表于 2022年4月3日 07:25:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/71721883.html
匿名

发表评论

匿名网友

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

确定