Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for config struct validate tags #1015

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ func WithConfigYamlDir[T any](dir string) ConfigOption[T] {
}
}

type ValidationError struct {
FailedField string `json:"failed_field"` // the field that failed to be validated
Tag string `json:"tag"`
Value string `json:"value"`
Type string `json:"type"`
Message string `json:"message"` // a description of the error that occured
}

func (e ValidationError) Error() string {
return e.Message
}

// LoadConfiguration loads the configuration from the app-config.yaml and app-config.<env>.yaml files
func LoadConfiguration[T any](cfg *T, opts ...ConfigOption[T]) error {
configYamlDir := defaultConfigYamlDir
Expand All @@ -63,6 +75,8 @@ func LoadConfiguration[T any](cfg *T, opts ...ConfigOption[T]) error {
}
}

// TODO: apply defaults?

loader.populateConfiguration(cfg)

for _, fn := range loader.ConfigEditors {
Expand All @@ -72,7 +86,7 @@ func LoadConfiguration[T any](cfg *T, opts ...ConfigOption[T]) error {
}
}

return nil
return validateConfiguration(cfg)
hspitzley-czi marked this conversation as resolved.
Show resolved Hide resolved
}

func (c *ConfigLoader[T]) populateConfiguration(cfg *T) error {
Expand Down
9 changes: 8 additions & 1 deletion config/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ module github.com/chanzuckerberg/go-misc/config/v2
go 1.21.1

require (
github.com/go-playground/locales v0.14.1
github.com/go-playground/universal-translator v0.18.1
github.com/go-playground/validator/v10 v10.19.0
github.com/mitchellh/mapstructure v1.5.0
github.com/spf13/viper v1.18.2
github.com/stretchr/testify v1.8.4
Expand All @@ -11,7 +14,9 @@ require (
require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
Expand All @@ -24,8 +29,10 @@ require (
github.com/subosito/gotenv v1.6.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/crypto v0.19.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.17.0 // indirect
golang.org/x/text v0.14.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
20 changes: 18 additions & 2 deletions config/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.19.0 h1:ol+5Fu+cSq9JD7SoSqe04GMI92cbn0+wvQ3bZ8b/AU4=
github.com/go-playground/validator/v10 v10.19.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
Expand All @@ -14,6 +24,8 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
Expand Down Expand Up @@ -53,10 +65,14 @@ go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
100 changes: 100 additions & 0 deletions config/validation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package config

import (
"errors"
"fmt"
"reflect"
"sync"

"github.com/go-playground/locales/en"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
)

var (
once sync.Once
validate *validator.Validate
translatorMessages map[string](func() string)
translator ut.Translator
)

func init() {
once.Do(func() {
validate = validator.New()
// err := validate.RegisterValidation("valid_env", ValidateEnvironment)
// if err != nil {
// logrus.Fatal("Failed to register custom validation")
// }
// err = validate.RegisterValidation("valid_env_dest", ValidateEnvironmentCopyDestination)
// if err != nil {
// logrus.Fatal("Failed to register custom validation")
// }

en := en.New()
uni := ut.New(en, en)
translator, _ = uni.GetTranslator("en")

translatorMessages = map[string](func() string){
// "valid_env": func() string {
// envs := []string{}
// for env := range model.EnvironmentMapping {
// envs = append(envs, env)
// }
// return fmt.Sprintf("{0} must be one of %s", envs)
// },
// "valid_env_dest": func() string {
// return "Copying configs from source env to destination env as specified is not allowed"
// },
}

for tag, getMessage := range translatorMessages {
err := validate.RegisterTranslation(
tag,
translator,
func(ut ut.Translator) error {
return ut.Add(tag, getMessage(), true) // see universal-translator for details
},
// use a function that returns a function here so the tag can be memoized
func(violatedTag string) validator.TranslationFunc {
return func(ut ut.Translator, fe validator.FieldError) string {
t, _ := ut.T(violatedTag, fe.Field())
return t
}
}(tag),
)
if err != nil {
return fmt.Errorf("Failed to register custom validation error translator: %w", err)
hspitzley-czi marked this conversation as resolved.
Show resolved Hide resolved
}
}
})
}

func validateConfiguration[T any](cfg *T) []ValidationError {
var errs []ValidationError

err := validate.Struct(cfg)
if err != nil {
errSlice := &validator.ValidationErrors{}
errors.As(err, errSlice)
for _, err := range *errSlice {
var element ValidationError
field, _ := reflect.ValueOf(cfg).Type().FieldByName(err.Field())
element.FailedField = field.Tag.Get("json")
if element.FailedField == "" {
element.FailedField = field.Tag.Get("query")
}
element.Tag = err.Tag()
element.Value = err.Param()
element.Type = err.Kind().String()

if _, ok := translatorMessages[element.Tag]; ok {
element.Message = err.Translate(translator)
} else {
element.Message = fmt.Sprintf("Field validation for '%s' failed on the '%s' tag", element.FailedField, element.Tag)
}

errs = append(errs, &element)
hspitzley-czi marked this conversation as resolved.
Show resolved Hide resolved
}
}
return errs
}
Loading