From dfdb0b099206c973579f8467696d16f5f8154082 Mon Sep 17 00:00:00 2001 From: Rheisen Date: Tue, 6 Aug 2024 08:49:55 -0400 Subject: [PATCH] Add ability to override the default field set when filling a struct --- app_config.go | 4 ++++ app_config_test.go | 28 ++++++++++++++++++++++++++++ config_struct.go | 4 +++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/app_config.go b/app_config.go index e05014a..3084714 100644 --- a/app_config.go +++ b/app_config.go @@ -452,6 +452,10 @@ func (c *AppConfig) FillStruct(configStruct any) (err error) { baseFieldSet := configStructFieldType.Tag.Get("bconf") + if overrideValue := configStructField.FieldByName("FieldSet"); overrideValue.String() != "" { + baseFieldSet = overrideValue.String() + } + for i := 0; i < configStructValue.NumField(); i++ { field := configStructType.Field(i) diff --git a/app_config_test.go b/app_config_test.go index 8a6b837..74059bf 100644 --- a/app_config_test.go +++ b/app_config_test.go @@ -1621,6 +1621,20 @@ func TestAppConfigFillStruct(t *testing.T) { t.Fatalf("problem adding field set to AppConfig: %v\n", errs) } + errs = appConfig.AddFieldSet( + bconf.FSB().Key("ext_api").Fields( + bconf.FB().Key("host").Type(bconf.String).Default("0.0.0.0").Create(), + bconf.FB().Key("port").Type(bconf.Int).Default(8085).Create(), + bconf.FB().Key("read_timeout").Type(bconf.Duration).Default(10*time.Second).Create(), + bconf.FB().Key("db_switch_time").Type(bconf.Time).Default(dbSwitchTime).Create(), + bconf.FB().Key("debug_mode").Type(bconf.Bool).Default(true).Create(), + ).Create(), + ) + + if len(errs) > 0 { + t.Fatalf("problem adding field set to AppConfig: %v\n", errs) + } + unfillableStruct := TestAPIConfig{} if err := appConfig.FillStruct(unfillableStruct); err == nil { t.Fatalf("expected error passing concrete struct\n") @@ -1659,6 +1673,20 @@ func TestAppConfigFillStruct(t *testing.T) { if configStruct.DebugMode != true { t.Errorf("unexpected value for configStruct.Host ('%v'), expected: %v\n", configStruct.DebugMode, true) } + + overrideConfigStruct := &TestAPIConfig{ConfigStruct: bconf.ConfigStruct{FieldSet: "ext_api"}} + + if err := appConfig.FillStruct(overrideConfigStruct); err != nil { + t.Fatalf("problem setting override struct values from AppConfig: %s\n", err) + } + + if overrideConfigStruct.Host != "0.0.0.0" { + t.Errorf("unexpected value for overrideConfigStruct.Host ('%s'), expected: %s\n", configStruct.Host, "0.0.0.0") + } + + if overrideConfigStruct.Port != 8085 { + t.Errorf("unexpected value for overrideConfigStruct.Port ('%d'), expected: %d\n", configStruct.Port, 8085) + } } func createBaseAppConfig() *bconf.AppConfig { diff --git a/config_struct.go b/config_struct.go index c7539ad..498983a 100644 --- a/config_struct.go +++ b/config_struct.go @@ -1,3 +1,5 @@ package bconf -type ConfigStruct struct{} +type ConfigStruct struct { + FieldSet string +}