envvars/object.go

35 lines
696 B
Go
Raw Permalink Normal View History

2022-08-25 10:18:22 +02:00
package envvars
import (
"os"
"strings"
)
func Object[T any](key string, defaultValue T, converter func(string) (T, error)) T {
if v, ok := os.LookupEnv(key); ok {
if v2, err := converter(v); err == nil {
return v2
}
}
return defaultValue
}
func ObjectSlice[T any](key, sep string, defaultValue []T, converter func(string) (T, error)) []T {
return Object(key, defaultValue, func(s string) ([]T, error) {
if s == "" {
return []T{}, nil
}
splits := strings.Split(s, sep)
values := make([]T, 0, len(splits))
for _, s := range splits {
v, err := converter(s)
if err != nil {
return values, err
}
values = append(values, v)
}
return values, nil
})
}