Skip to content

Commit

Permalink
Add ability to override the default field set when filling a struct
Browse files Browse the repository at this point in the history
  • Loading branch information
Rheisen committed Aug 6, 2024
1 parent 3067340 commit dfdb0b0
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
4 changes: 4 additions & 0 deletions app_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
28 changes: 28 additions & 0 deletions app_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 3 additions & 1 deletion config_struct.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
package bconf

type ConfigStruct struct{}
type ConfigStruct struct {
FieldSet string
}

0 comments on commit dfdb0b0

Please sign in to comment.