Skip to content

Commit 4ab8b37

Browse files
authored
feat: support ignored value "-" for env tag (#338)
* feat: support ignored value "-" for env tag * fix test
1 parent 1cb1967 commit 4ab8b37

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

env.go

+8
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,10 @@ func doParseField(
367367
return err
368368
}
369369

370+
if params.Ignored {
371+
return nil
372+
}
373+
370374
if err := processField(refField, refTypeField, opts, params); err != nil {
371375
return err
372376
}
@@ -533,6 +537,7 @@ type FieldParams struct {
533537
NotEmpty bool
534538
Expand bool
535539
Init bool
540+
Ignored bool
536541
}
537542

538543
func parseFieldParams(field reflect.StructField, opts Options) (FieldParams, error) {
@@ -549,6 +554,7 @@ func parseFieldParams(field reflect.StructField, opts Options) (FieldParams, err
549554
Required: opts.RequiredIfNoDef,
550555
DefaultValue: defaultValue,
551556
HasDefaultValue: hasDefaultValue,
557+
Ignored: ownKey == "-",
552558
}
553559

554560
for _, tag := range tags {
@@ -567,6 +573,8 @@ func parseFieldParams(field reflect.StructField, opts Options) (FieldParams, err
567573
result.Expand = true
568574
case "init":
569575
result.Init = true
576+
case "-":
577+
result.Ignored = true
570578
default:
571579
return FieldParams{}, newNoSupportedTagOptionError(tag)
572580
}

env_test.go

+40
Original file line numberDiff line numberDiff line change
@@ -2214,3 +2214,43 @@ func TestParseWithOptionsRenamedPrefix(t *testing.T) {
22142214
isNoErr(t, Parse(cfg))
22152215
isEqual(t, "101", cfg.Foo.Str)
22162216
}
2217+
2218+
func TestFieldIgnored(t *testing.T) {
2219+
type Test struct {
2220+
Foo string `env:"FOO"`
2221+
Bar string `env:"BAR,-"`
2222+
}
2223+
type ComplexConfig struct {
2224+
Str string `env:"STR"`
2225+
Foo Test `env:"FOO" envPrefix:"FOO_"`
2226+
Bar Test `env:"-" envPrefix:"BAR_"`
2227+
}
2228+
t.Setenv("STR", "101")
2229+
t.Setenv("FOO_FOO", "202")
2230+
t.Setenv("FOO_BAR", "303")
2231+
t.Setenv("BAR_FOO", "404")
2232+
t.Setenv("BAR_BAR", "505")
2233+
2234+
var cfg ComplexConfig
2235+
isNoErr(t, Parse(&cfg))
2236+
isEqual(t, "101", cfg.Str)
2237+
isEqual(t, "202", cfg.Foo.Foo)
2238+
isEqual(t, "", cfg.Foo.Bar)
2239+
isEqual(t, "", cfg.Bar.Foo)
2240+
isEqual(t, "", cfg.Bar.Bar)
2241+
}
2242+
2243+
func TestNoEnvKeyIgnored(t *testing.T) {
2244+
type Config struct {
2245+
Foo string `env:"-"`
2246+
FooBar string
2247+
}
2248+
2249+
t.Setenv("FOO", "101")
2250+
t.Setenv("FOO_BAR", "202")
2251+
2252+
var cfg Config
2253+
isNoErr(t, ParseWithOptions(&cfg, Options{UseFieldNameByDefault: true}))
2254+
isEqual(t, "", cfg.Foo)
2255+
isEqual(t, "202", cfg.FooBar)
2256+
}

0 commit comments

Comments
 (0)