Select Git revision
composer.lock
-
Christel Loftus authoredChristel Loftus authored
named_values_to_struct.go 11.00 KiB
package struct_utils
import (
"database/sql"
"encoding/csv"
"encoding/json"
"reflect"
"sort"
"strconv"
"strings"
"gitlab.com/uafrica/go-utils/errors"
"gitlab.com/uafrica/go-utils/logs"
"gitlab.com/uafrica/go-utils/string_utils"
)
//Purpose:
// Make a list of named values from the env for parsing into a struct
//
//Parameters:
// prefix should be uppercase (by convention) env prefix like "MY_LIB_CONFIG", without trailing "_"
//
//Result:
// named values that can be passed into UnmarshalNamedValues()
//
//All env starting with "<prefix>_" will be copied without "<prefix>_"
//Examples with prefix="MY_LIB_CONFIG":
// MY_LIB_CONFIG_MAX_SIZE="6" -> {"MAX_SIZE":["6"]} one value of "6"
// MY_LIB_CONFIG_NAMES ="A,B,C" -> {"NAMES":["A,B,C"]} one value of "A,B,C"
// MY_LIB_CONFIG_NRS ="1,2,3" -> {"NRS":["1,2,3"]} one value of "1,2,3" (all env values are string, later parsed into int based on struct field type)
// MY_LIB_CONFIG_CODES ="[1,2,3]"" -> {"CODES":["1","2","3"]} 3 values of "1", "2" and "3" because of outer [...], env values are string
//
// MY_LIB_CONFIG_CODES_1=5
// MY_LIB_CONFIG_CODES_5=7
// MY_LIB_CONFIG_CODES_2=10 -> {"CODES":["5","10","7"]} 3 values ordered on suffixes "_1", "_5", "_2" moving 10 before 7
//
// MY_LIB_CONFIG_ADDRS=["55 Crescent, Town", "12 Big Street, City"] -> 2 values including commas because of quoted CSV
func NamedValuesFromEnv(prefix string) map[string][]string {
return NamedValuesFromReader(prefix, string_utils.EnvironmentKeyReader())
}
func NamedValuesFromReader(prefix string, reader string_utils.KeyReader) map[string][]string {
if reader == nil {
return nil
}
result := map[string][]string{}
prefix += "_"
for _, key := range reader.Keys(prefix) {
value, ok := reader.GetString(key)
key = key[len(prefix):]
if !ok {
logs.Warn("Key(%s) undefined", key)
continue
}
result[strings.ToLower(key)] = []string{value}
//split only if valid CSV between [...]
if value[0] == '[' && value[len(value)-1] == ']' {
csvReader := csv.NewReader(strings.NewReader(value[1 : len(value)-1]))
csvValues, csvErr := csvReader.Read() //this automatically removes quotes around some/all CSV inside the [...]
if csvErr == nil {
result[strings.ToLower(key)] = csvValues
}
}
}
//merge multiple <name>_#=<value> into single lists called <name>
namesToDelete := []string{}
merged := map[string][]nrWithValues{}
for name, values := range result {