Last active
December 5, 2020 03:15
-
-
Save SkYNewZ/23aea78291be421a956d0874e5571ebb to your computer and use it in GitHub Desktop.
Check that each strings fields in a Struct are non-zero value using reflect and return error contains specific tag value
This file contains 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
// validate ensure all required secrets are set up | |
func (secrets *s) validate(sub ...interface{}) error { | |
// Reflect it | |
v := reflect.ValueOf(*secrets) | |
if len(sub) > 0 { | |
// Recursive | |
v = reflect.ValueOf(sub[0]) | |
} | |
// Iterate over each fields and looks from empty string | |
for i := 0; i < v.NumField(); i++ { | |
switch v.Field(i).Kind() { | |
case reflect.String: | |
if v.Field(i).IsZero() { | |
fields, ok := v.Type().FieldByName(v.Type().Field(i).Name) | |
var missingField = v.Type().Field(i).Name | |
if ok { | |
missingField = fields.Tag.Get("mapstructure") | |
} | |
return fmt.Errorf("LoadConfigFromVault(): %q key is missing on Vault (using %s secrets path)", missingField, requiredSecrets) | |
} | |
case reflect.Struct: | |
if err := secrets.validate(v.Field(i).Interface()); err != nil { | |
return err | |
} | |
default: | |
panic("missing type implementation") | |
} | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment