Skip to content

Commit

Permalink
Add Sub method on Builder, which populates the given struct starting …
Browse files Browse the repository at this point in the history
…at the provided prefix.
  • Loading branch information
JeremyLoy committed Jul 27, 2021
1 parent ce46d0e commit 62420be
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
11 changes: 10 additions & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,20 @@ func newBuilder() *Builder {
// It panics if:
// * target is not a struct pointer
func (c *Builder) To(target interface{}) error {
return c.decode(target, "")
}

// Sub behaves the same as To, however it maps configuration to the struct starting at the given prefix.
func (c *Builder) Sub(target interface{}, prefix string) error {
return c.decode(target, prefix+c.structDelim)
}

func (c *Builder) decode(target interface{}, prefix string) error {
structPtr := reflect.ValueOf(target)
if structPtr.Kind() != reflect.Ptr || structPtr.Elem().Kind() != reflect.Struct {
panic("config: To(target) must be a *struct")
}
c.populateStructRecursively(structPtr, "")
c.populateStructRecursively(structPtr, prefix)
if c.failedFields != nil {
return fmt.Errorf("config: the following fields had errors: %v", c.failedFields)
}
Expand Down
5 changes: 5 additions & 0 deletions config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ func Test_Integration(t *testing.T) {
got := testConfig{
K: "hardcoded",
}
var sub D
want := testConfig{
A: 1,
B: "overridden",
Expand All @@ -90,9 +91,13 @@ func Test_Integration(t *testing.T) {

builder := From(file.Name()).From("nonexistfile").FromEnv()
gotErr := builder.To(&got)
_ = builder.Sub(&sub, "dog")
if !reflect.DeepEqual(got, want) {
t.Errorf("Integration: got %+v, want %+v", got, want)
}
if !reflect.DeepEqual(sub, want.D) {
t.Errorf("Integration: got %+v, want %+v", sub, want.D)
}
if gotErr == nil {
t.Errorf("Integration: should have had an error")
}
Expand Down
13 changes: 13 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,19 @@ func Example() {
// [0.0.0.0 1.1.1.1 2.2.2.2] 3
}

func Example_subconfig() {
os.Clearenv()
os.Setenv("SUBCONFIG__IPWHITELIST", "0.0.0.0 1.1.1.1 2.2.2.2")

var c MySubConfig
config.FromEnv().Sub(&c, "SUBCONFIG")

fmt.Println(c.IPWhitelist, len(c.IPWhitelist))

// Output:
// [0.0.0.0 1.1.1.1 2.2.2.2] 3
}

func Example_defaults() {
os.Clearenv()
os.Setenv("DATABASE_URL", "production://")
Expand Down

0 comments on commit 62420be

Please sign in to comment.