Skip to content

Commit db7a7a5

Browse files
authored
Introduce the LookuperFunc type to simplify the creation of custom implementations of the Lookuper interface (#129)
* Add LookuperFunc type to implement Lookuper interface * Add test cases for LookuperFunc
1 parent 7ee4127 commit db7a7a5

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

envconfig.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,17 @@ type Lookuper interface {
108108
Lookup(key string) (string, bool)
109109
}
110110

111+
var _ Lookuper = (LookuperFunc)(nil)
112+
113+
// LookuperFunc implements the [Lookuper] interface and provides a quick way to
114+
// create an anonymous function that performs a lookup for a string-based key.
115+
type LookuperFunc func(key string) (string, bool)
116+
117+
// Lookup implements [Lookuper].
118+
func (l LookuperFunc) Lookup(key string) (string, bool) {
119+
return l(key)
120+
}
121+
111122
// osLookuper looks up environment configuration from the local environment.
112123
type osLookuper struct{}
113124

envconfig_test.go

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2930,6 +2930,70 @@ func TestProcessWith(t *testing.T) {
29302930
"FIELD": "foo bar,zip:zap zoo:zil",
29312931
}),
29322932
},
2933+
// LookuperFunc
2934+
{
2935+
name: "lookuperfunc/static",
2936+
target: &struct {
2937+
Field1 string `env:"FIELD1"`
2938+
Field2 string `env:"FIELD2"`
2939+
}{},
2940+
lookuper: LookuperFunc(func(key string) (string, bool) {
2941+
return "foo", true
2942+
}),
2943+
exp: &struct {
2944+
Field1 string `env:"FIELD1"`
2945+
Field2 string `env:"FIELD2"`
2946+
}{
2947+
Field1: "foo",
2948+
Field2: "foo",
2949+
},
2950+
},
2951+
{
2952+
name: "lookuperfunc/branching",
2953+
target: &struct {
2954+
Field1 string `env:"FIELD1"`
2955+
Field2 string `env:"FIELD2"`
2956+
}{},
2957+
lookuper: LookuperFunc(func(key string) (string, bool) {
2958+
if key == "FIELD1" {
2959+
return "foo", true
2960+
}
2961+
return "", false
2962+
}),
2963+
exp: &struct {
2964+
Field1 string `env:"FIELD1"`
2965+
Field2 string `env:"FIELD2"`
2966+
}{
2967+
Field1: "foo",
2968+
Field2: "",
2969+
},
2970+
},
2971+
{
2972+
name: "lookuperfunc/switching",
2973+
target: &struct {
2974+
Field1 string `env:"FIELD1"`
2975+
Field2 string `env:"FIELD2"`
2976+
Field3 string `env:"FIELD3"`
2977+
}{},
2978+
lookuper: LookuperFunc(func(key string) (string, bool) {
2979+
switch key {
2980+
case "FIELD1":
2981+
return "foo", true
2982+
case "FIELD2":
2983+
return "bar", true
2984+
}
2985+
return "", false
2986+
}),
2987+
exp: &struct {
2988+
Field1 string `env:"FIELD1"`
2989+
Field2 string `env:"FIELD2"`
2990+
Field3 string `env:"FIELD3"`
2991+
}{
2992+
Field1: "foo",
2993+
Field2: "bar",
2994+
Field3: "",
2995+
},
2996+
},
29332997
}
29342998

29352999
for _, tc := range cases {

0 commit comments

Comments
 (0)