diff --git a/env.go b/env.go index e62b222..246d6c7 100644 --- a/env.go +++ b/env.go @@ -140,6 +140,9 @@ type Options struct { // TagName specifies another tag name to use rather than the default 'env'. TagName string + // PrefixTagName specifies another prefix tag name to use rather than the default 'envPrefix'. + PrefixTagName string + // DefaultValueTagName specifies another default tag name to use rather than the default 'envDefault'. DefaultValueTagName string @@ -178,6 +181,7 @@ func (opts *Options) getRawEnv(s string) string { func defaultOptions() Options { return Options{ TagName: "env", + PrefixTagName: "envPrefix", DefaultValueTagName: "envDefault", Environment: toMap(os.Environ()), FuncMap: defaultTypeParsers(), @@ -190,6 +194,9 @@ func customOptions(opt Options) Options { if opt.TagName == "" { opt.TagName = defOpts.TagName } + if opt.PrefixTagName == "" { + opt.PrefixTagName = defOpts.PrefixTagName + } if opt.DefaultValueTagName == "" { opt.DefaultValueTagName = defOpts.DefaultValueTagName } @@ -214,6 +221,7 @@ func optionsWithSliceEnvPrefix(opts Options, index int) Options { return Options{ Environment: opts.Environment, TagName: opts.TagName, + PrefixTagName: opts.PrefixTagName, DefaultValueTagName: opts.DefaultValueTagName, RequiredIfNoDef: opts.RequiredIfNoDef, OnSet: opts.OnSet, @@ -228,10 +236,11 @@ func optionsWithEnvPrefix(field reflect.StructField, opts Options) Options { return Options{ Environment: opts.Environment, TagName: opts.TagName, + PrefixTagName: opts.PrefixTagName, DefaultValueTagName: opts.DefaultValueTagName, RequiredIfNoDef: opts.RequiredIfNoDef, OnSet: opts.OnSet, - Prefix: opts.Prefix + field.Tag.Get("envPrefix"), + Prefix: opts.Prefix + field.Tag.Get(opts.PrefixTagName), UseFieldNameByDefault: opts.UseFieldNameByDefault, FuncMap: opts.FuncMap, rawEnvVars: opts.rawEnvVars, diff --git a/env_test.go b/env_test.go index 69b1713..8a4daee 100644 --- a/env_test.go +++ b/env_test.go @@ -2191,3 +2191,26 @@ func TestParseWithOptionsRenamedDefault(t *testing.T) { isNoErr(t, Parse(cfg)) isEqual(t, "foo", cfg.Str) } + +func TestParseWithOptionsRenamedPrefix(t *testing.T) { + type Config struct { + Str string `env:"STR"` + } + type ComplexConfig struct { + Foo Config `envPrefix:"FOO_" myPrefix:"BAR_"` + } + + t.Setenv("FOO_STR", "101") + t.Setenv("BAR_STR", "202") + t.Setenv("APP_BAR_STR", "303") + + cfg := &ComplexConfig{} + isNoErr(t, ParseWithOptions(cfg, Options{PrefixTagName: "myPrefix"})) + isEqual(t, "202", cfg.Foo.Str) + + isNoErr(t, ParseWithOptions(cfg, Options{PrefixTagName: "myPrefix", Prefix: "APP_"})) + isEqual(t, "303", cfg.Foo.Str) + + isNoErr(t, Parse(cfg)) + isEqual(t, "101", cfg.Foo.Str) +}