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

Time:04-08

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?

CodePudding user response:

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

  • Related