Created
April 13, 2022 21:36
-
-
Save housingdreams/3bd0ee56a46adc313255aa196b436497 to your computer and use it in GitHub Desktop.
Example of adding validation to a json unmarshal for things like required fields or regex validation via github.com/asaskevich/govalidator or https://github.com/go-playground/validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| func UnmarshalWithValidation(data []byte, p interface{}) error { | |
| err := json.Unmarshal(data, p) | |
| if err != nil { | |
| return err | |
| } | |
| isValid, err := govalidator.ValidateStruct(p) | |
| if err != nil { | |
| return err | |
| } | |
| if !isValid { | |
| return govalidator.ErrorsByField(err) | |
| } | |
| return nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment