diff --git a/conf.v b/conf.v index cfe137f..564f7e8 100644 --- a/conf.v +++ b/conf.v @@ -40,9 +40,9 @@ fn get_env_var(prefix string, field_name string, file_suffix string) !string { [params] pub struct LoadConfig { - prefix string - file_suffix string = '_FILE' - default_path string + prefix string + file_suffix string = '_FILE' + default_path string } // load attempts to create an object of type T from the given path to a toml @@ -52,8 +52,12 @@ pub struct LoadConfig { pub fn load(conf LoadConfig) !T { mut res := T{} - // Later, this could be read from an env var as well. - path := conf.default_path + // This array allows us to determine later whether the variable is actually + // zero or just a null'ed struct field + mut has_value := map[string]bool{} + + // Later, this could be read from an env var as well. + path := conf.default_path if os.exists(path) { // We don't use reflect here because reflect also sets any fields not @@ -68,7 +72,11 @@ pub fn load(conf LoadConfig) !T { res.$(field.name) = s.string() } $else $if field.typ is int { res.$(field.name) = s.int() + } $else { + $compile_error('Unsupported config struct field type detected.') } + + has_value[field.name] = true } } } @@ -83,20 +91,14 @@ pub fn load(conf LoadConfig) !T { res.$(field.name) = env_value } $else $if field.typ is int { res.$(field.name) = env_value.int() + } $else { + $compile_error('Unsupported config struct field type detected.') } + + has_value[field.name] = true } - // Now, we check whether a value is present. If there isn't, that means - // it isn't in the config file, nor is there a default or an env var. - mut has_value := false - - $if field.typ is string { - has_value = res.$(field.name) != '' - } $else $if field.typ is int { - has_value = res.$(field.name) != 0 - } - - if !has_value { + if !(has_values[field.name] or { false }) { return error("Missing config variable '$field.name' with no provided default. Either add it to the config file or provide it using an environment variable.") } }