From 0d8016d665dd7a8876dba754ad17b910c24cf033 Mon Sep 17 00:00:00 2001 From: Oleg Kovalov Date: Mon, 6 Sep 2021 17:58:51 +0200 Subject: [PATCH] Fix omitempty in tags (#107) --- aconfig_test.go | 18 ++++++++++++++++++ reflection.go | 3 +++ 2 files changed, 21 insertions(+) diff --git a/aconfig_test.go b/aconfig_test.go index e22d413..f91002d 100644 --- a/aconfig_test.go +++ b/aconfig_test.go @@ -167,6 +167,24 @@ func TestJSON(t *testing.T) { } } +func TestJSONWithOmitempty(t *testing.T) { + type TestConfig struct { + APIKey string `json:"b,omitempty"` + } + + var cfg TestConfig + loader := LoaderFor(&cfg, Config{ + SkipDefaults: true, + SkipEnv: true, + SkipFlags: true, + AllowUnknownFields: true, + Files: []string{createTestFile(t)}, + }) + if err := loader.Load(); err != nil { + t.Fatal(err) + } +} + func TestCustomFile(t *testing.T) { filepath := createTestFile(t, "custom.config") diff --git a/reflection.go b/reflection.go index 891a207..07c6b97 100644 --- a/reflection.go +++ b/reflection.go @@ -84,6 +84,9 @@ func (l *Loader) fullTag(prefix string, f *fieldData, tag string) string { if before, _, ok := cut(res, ",exact"); ok { return before } + if before, _, ok := cut(res, ",omitempty"); ok { + return before + } for p := f.parent; p != nil; p = p.parent { if p.Tag(tag) != "-" { res = p.Tag(tag) + sep + res