github.com/christoph-karpowicz/db_mediator@v0.0.0-20210207102849-61a28a1071d8/internal/util/validation/yaml.go (about)

     1  package validationUtil
     2  
     3  import (
     4  	"reflect"
     5  	"strconv"
     6  	"strings"
     7  
     8  	"github.com/christoph-karpowicz/db_mediator/internal/util"
     9  )
    10  
    11  func YAMLField(fieldValue interface{}, fieldName string) bool {
    12  	switch fieldValue.(type) {
    13  	case int:
    14  		if fieldValue.(int) <= 0 {
    15  			return false
    16  		}
    17  	case string:
    18  		if len(fieldValue.(string)) <= 0 {
    19  			return false
    20  		}
    21  	case []string:
    22  		if len(fieldValue.([]string)) == 0 {
    23  			return false
    24  		}
    25  		for i, val := range fieldValue.([]string) {
    26  			if !YAMLField(val, strconv.Itoa(i)) {
    27  				return false
    28  			}
    29  		}
    30  	}
    31  	return true
    32  }
    33  
    34  func YAMLStruct(structure interface{}, nullableFields []string) {
    35  	fieldValue := reflect.ValueOf(structure)
    36  	fieldType := fieldValue.Type()
    37  
    38  	for i := 0; i < fieldValue.NumField(); i++ {
    39  
    40  		// If a field doesn't have a tag, it means it's value wasn't imported from YAML file.
    41  		if fieldType.Field(i).Tag == "" {
    42  			continue
    43  		}
    44  
    45  		if !YAMLField(fieldValue.Field(i).Interface(), fieldType.Field(i).Name) {
    46  			if !util.StringSliceContains(nullableFields, strings.ToLower(fieldType.Field(i).Name)) {
    47  				panic(fieldType.Field(i).Name + " is invalid.")
    48  			}
    49  		}
    50  
    51  	}
    52  }