From 4ab8b371a1e3f57c04bc0531d6e99773e9297564 Mon Sep 17 00:00:00 2001 From: Sergey Kozlov Date: Fri, 11 Oct 2024 22:20:46 +0300 Subject: [PATCH] feat: support ignored value "-" for env tag (#338) * feat: support ignored value "-" for env tag * fix test --- env.go | 8 ++++++++ env_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/env.go b/env.go index 246d6c7..d24c32e 100644 --- a/env.go +++ b/env.go @@ -367,6 +367,10 @@ func doParseField( return err } + if params.Ignored { + return nil + } + if err := processField(refField, refTypeField, opts, params); err != nil { return err } @@ -533,6 +537,7 @@ type FieldParams struct { NotEmpty bool Expand bool Init bool + Ignored bool } func parseFieldParams(field reflect.StructField, opts Options) (FieldParams, error) { @@ -549,6 +554,7 @@ func parseFieldParams(field reflect.StructField, opts Options) (FieldParams, err Required: opts.RequiredIfNoDef, DefaultValue: defaultValue, HasDefaultValue: hasDefaultValue, + Ignored: ownKey == "-", } for _, tag := range tags { @@ -567,6 +573,8 @@ func parseFieldParams(field reflect.StructField, opts Options) (FieldParams, err result.Expand = true case "init": result.Init = true + case "-": + result.Ignored = true default: return FieldParams{}, newNoSupportedTagOptionError(tag) } diff --git a/env_test.go b/env_test.go index 8a4daee..3ccaae4 100644 --- a/env_test.go +++ b/env_test.go @@ -2214,3 +2214,43 @@ func TestParseWithOptionsRenamedPrefix(t *testing.T) { isNoErr(t, Parse(cfg)) isEqual(t, "101", cfg.Foo.Str) } + +func TestFieldIgnored(t *testing.T) { + type Test struct { + Foo string `env:"FOO"` + Bar string `env:"BAR,-"` + } + type ComplexConfig struct { + Str string `env:"STR"` + Foo Test `env:"FOO" envPrefix:"FOO_"` + Bar Test `env:"-" envPrefix:"BAR_"` + } + t.Setenv("STR", "101") + t.Setenv("FOO_FOO", "202") + t.Setenv("FOO_BAR", "303") + t.Setenv("BAR_FOO", "404") + t.Setenv("BAR_BAR", "505") + + var cfg ComplexConfig + isNoErr(t, Parse(&cfg)) + isEqual(t, "101", cfg.Str) + isEqual(t, "202", cfg.Foo.Foo) + isEqual(t, "", cfg.Foo.Bar) + isEqual(t, "", cfg.Bar.Foo) + isEqual(t, "", cfg.Bar.Bar) +} + +func TestNoEnvKeyIgnored(t *testing.T) { + type Config struct { + Foo string `env:"-"` + FooBar string + } + + t.Setenv("FOO", "101") + t.Setenv("FOO_BAR", "202") + + var cfg Config + isNoErr(t, ParseWithOptions(&cfg, Options{UseFieldNameByDefault: true})) + isEqual(t, "", cfg.Foo) + isEqual(t, "202", cfg.FooBar) +}