nuclei/v2/pkg/utils/yaml/yaml_decode_wrapper.go
forgedhallpass ec6889931d refactor: linter driven fixes
* x = x + ""  => x += ""
* pre-allocating slice with known size
* added t.Helper() methods in test helpers
* complex if-else conditions replaced by switches
* errors should be checked using error.Is() instead of ==
* function parameter should start with lower case letter
* removed unnecessary type definition
* variable/label naming convention: camelCase instead of snake_case
2021-11-25 17:57:22 +02:00

35 lines
797 B
Go

package yaml
import (
"io"
"strings"
"github.com/go-playground/validator/v10"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
var validate *validator.Validate
// DecodeAndValidate is a wrapper for yaml Decode adding struct validation
func DecodeAndValidate(r io.Reader, v interface{}) error {
if err := yaml.NewDecoder(r).Decode(v); err != nil {
return err
}
if validate == nil {
validate = validator.New()
}
if err := validate.Struct(v); err != nil {
if _, ok := err.(*validator.InvalidValidationError); ok {
return err
}
errs := []string{}
for _, err := range err.(validator.ValidationErrors) {
errs = append(errs, err.Namespace()+": "+err.Tag())
}
return errors.Wrap(errors.New(strings.Join(errs, ", ")), "validation failed for these fields")
}
return nil
}