Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 53 additions & 59 deletions core/conf/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,11 @@ func Load(file string, v any, opts ...Option) error {
}

if opt.env {
return loader([]byte(os.ExpandEnv(string(content))), v)
expanded, err := expandEnv(string(content))
if err != nil {
return err
}
content = []byte(expanded)
}

return loader(content, v)
Expand All @@ -84,7 +88,10 @@ func LoadFromJsonBytes(content []byte, v any) error {
return err
}

lowerCaseKeyMap := toLowerCaseKeyMap(m, info)
lowerCaseKeyMap, err := toLowerCaseKeyMap(m, info)
if err != nil {
return err
}

if err = mapping.UnmarshalJsonMap(lowerCaseKeyMap, v,
mapping.WithCanonicalKeyFunc(toLowerCase)); err != nil {
Expand Down Expand Up @@ -182,10 +189,7 @@ func buildAnonymousFieldInfo(info *fieldInfo, lowerCaseName string, ft reflect.T
return newConflictKeyError(fullName)
}

info.children[lowerCaseName] = &fieldInfo{
children: make(map[string]*fieldInfo),
mapField: elemField,
}
info.children[lowerCaseName] = &fieldInfo{mapField: elemField}
default:
if _, ok := info.children[lowerCaseName]; ok {
return newConflictKeyError(fullName)
Expand All @@ -205,8 +209,15 @@ func buildFieldsInfo(tp reflect.Type, fullName string) (*fieldInfo, error) {
switch tp.Kind() {
case reflect.Struct:
return buildStructFieldsInfo(tp, fullName)
case reflect.Array, reflect.Slice, reflect.Map:
return buildFieldsInfo(mapping.Deref(tp.Elem()), fullName)
case reflect.Array, reflect.Slice:
return buildFieldsInfo(tp.Elem(), fullName)
case reflect.Map:
elemInfo, err := buildFieldsInfo(tp.Elem(), fullName)
if err != nil {
return nil, err
}

return &fieldInfo{mapField: elemInfo}, nil
case reflect.Chan, reflect.Func:
return nil, fmt.Errorf("unsupported type: %s, fullName: %s", tp.Kind(), fullName)
default:
Expand All @@ -217,35 +228,9 @@ func buildFieldsInfo(tp reflect.Type, fullName string) (*fieldInfo, error) {
}

func buildNamedFieldInfo(info *fieldInfo, lowerCaseName string, ft reflect.Type, fullName string) error {
var finfo *fieldInfo
var err error

switch ft.Kind() {
case reflect.Struct:
finfo, err = buildFieldsInfo(ft, fullName)
if err != nil {
return err
}
case reflect.Array, reflect.Slice:
finfo, err = buildFieldsInfo(ft.Elem(), fullName)
if err != nil {
return err
}
case reflect.Map:
elemInfo, err := buildFieldsInfo(mapping.Deref(ft.Elem()), fullName)
if err != nil {
return err
}

finfo = &fieldInfo{
children: make(map[string]*fieldInfo),
mapField: elemInfo,
}
default:
finfo, err = buildFieldsInfo(ft, fullName)
if err != nil {
return err
}
finfo, err := buildFieldsInfo(ft, fullName)
if err != nil {
return err
}

return addOrMergeFields(info, lowerCaseName, finfo, fullName)
Expand Down Expand Up @@ -318,44 +303,53 @@ func toLowerCase(s string) string {
return strings.ToLower(s)
}

func toLowerCaseInterface(v any, info *fieldInfo) any {
func toLowerCaseInterface(v any, info *fieldInfo) (any, error) {
switch vv := v.(type) {
case map[string]any:
return toLowerCaseKeyMap(vv, info)
case []any:
arr := make([]any, 0, len(vv))
for _, vvv := range vv {
arr = append(arr, toLowerCaseInterface(vvv, info))
arr := make([]any, len(vv))
for i, elem := range vv {
value, err := toLowerCaseInterface(elem, info)
if err != nil {
return nil, fmt.Errorf("element %d: %w", i, err)
}
arr[i] = value
}
return arr
return arr, nil
default:
return v
return v, nil
}
}

func toLowerCaseKeyMap(m map[string]any, info *fieldInfo) map[string]any {
res := make(map[string]any)
func toLowerCaseKeyMap(m map[string]any, info *fieldInfo) (map[string]any, error) {
res := make(map[string]any, len(m))
seen := make(map[string]string)

for k, v := range m {
ti, ok := info.children[k]
if ok {
res[k] = toLowerCaseInterface(v, ti)
continue
key := k
child := info.mapField
if lower := toLowerCase(k); info.children[lower] != nil {
if previous, ok := seen[lower]; ok {
Comment on lines +332 to +333
first, second := min(previous, k), max(previous, k)
return nil, fmt.Errorf("ambiguous config keys %q and %q both map to field %q",
first, second, lower)
}
seen[lower] = k
key, child = lower, info.children[lower]
}

lk := toLowerCase(k)
if ti, ok = info.children[lk]; ok {
res[lk] = toLowerCaseInterface(v, ti)
} else if info.mapField != nil {
res[k] = toLowerCaseInterface(v, info.mapField)
} else if vv, ok := v.(map[string]any); ok {
res[k] = toLowerCaseKeyMap(vv, info)
} else {
res[k] = v
if child != nil {
normalized, err := toLowerCaseInterface(v, child)
if err != nil {
return nil, fmt.Errorf("config key %q: %w", k, err)
}
v = normalized
}
res[key] = v
}

return res
return res, nil
}

type conflictKeyError struct {
Expand Down
67 changes: 63 additions & 4 deletions core/conf/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zeromicro/go-zero/core/fs"
"github.com/zeromicro/go-zero/core/hash"
)
Expand Down Expand Up @@ -153,7 +154,7 @@ func TestConfigJson5Env(t *testing.T) {
a: "foo",
b: 1,
c: "${FOO}",
d: "abcd!@#$a12 3",
d: "abcd!@#$$a12 3",
}`
t.Setenv("FOO", "2")

Expand All @@ -170,7 +171,7 @@ func TestConfigJson5Env(t *testing.T) {
assert.Equal(t, "foo", val.A)
assert.Equal(t, 1, val.B)
assert.Equal(t, "2", val.C)
assert.Equal(t, "abcd!@# 3", val.D)
assert.Equal(t, "abcd!@#$a12 3", val.D)
}

func TestLoadFromJson5Bytes(t *testing.T) {
Expand Down Expand Up @@ -385,7 +386,7 @@ func TestConfigJsonEnv(t *testing.T) {
"a": "foo",
"b": 1,
"c": "${FOO}",
"d": "abcd!@#$a12 3"
"d": "abcd!@#$$a12 3"
}`
t.Setenv("FOO", "2")
for _, test := range tests {
Expand All @@ -404,11 +405,69 @@ func TestConfigJsonEnv(t *testing.T) {
assert.Equal(t, "foo", val.A)
assert.Equal(t, 1, val.B)
assert.Equal(t, "2", val.C)
assert.Equal(t, "abcd!@# 3", val.D)
assert.Equal(t, "abcd!@#$a12 3", val.D)
})
}
}

func TestLoadWithUnsetEnv(t *testing.T) {
const name = "GO_ZERO_CONF_TEST_UNSET"
t.Setenv(name, "")
require.NoError(t, os.Unsetenv(name))

file, err := createTempFile(t, ".yaml", "password: prefix-$"+name)
require.NoError(t, err)

var cfg struct{ Password string }
require.ErrorContains(t, Load(file, &cfg, UseEnv()), name)
require.Empty(t, cfg.Password)
require.NoError(t, Load(file, &cfg))
require.Equal(t, "prefix-$"+name, cfg.Password)
}

func TestLoadRejectsAmbiguousConfigKeys(t *testing.T) {
type auth struct {
Token string
}
type config struct {
Auth *auth `json:",optional"`
Services []auth `json:",optional"`
Accounts map[string]map[string]auth `json:",optional"`
}

tests := []struct {
name string
input string
err string
}{
{"root", `{"Auth":null,"AUTH":null}`, `ambiguous config keys "AUTH" and "Auth" both map to field "auth"`},
{"nested", `{"Auth":{"Token":"one","token":"two"}}`, `config key "Auth": ambiguous config keys "Token" and "token"`},
{"slice", `{"Services":[{"Token":"one","token":"two"}]}`, `config key "Services": element 0: ambiguous config keys "Token" and "token"`},
{"map", `{"Accounts":{"Primary":{"Token":{"Token":"one","token":"two"}}}}`, `config key "Token": ambiguous config keys "Token" and "token"`},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var cfg config
require.ErrorContains(t, LoadFromJsonBytes([]byte(test.input), &cfg), test.err)
require.Equal(t, config{}, cfg)
})
}

var cfg config
require.NoError(t, LoadFromYamlBytes([]byte(`
Accounts:
Primary:
Token:
TOKEN: one
token:
token: two
Ignored:
Auth: one
auth: two
`), &cfg))
require.Equal(t, map[string]auth{"Token": {Token: "one"}, "token": {Token: "two"}}, cfg.Accounts["Primary"])
}

func TestToCamelCase(t *testing.T) {
tests := []struct {
input string
Expand Down
32 changes: 31 additions & 1 deletion core/conf/options.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
package conf

import (
"fmt"
"os"
"regexp"
)

type (
// Option defines the method to customize the config options.
Option func(opt *options)
Expand All @@ -9,9 +15,33 @@ type (
}
)

// UseEnv customizes the config to use environment variables.
// UseEnv expands $NAME and ${NAME} references when loading configuration.
// Use $$ for a literal dollar. Referencing an unset variable returns an error.
func UseEnv() Option {
return func(opt *options) {
opt.env = true
}
}

var envReference = regexp.MustCompile(`\$\$|\$\{[^{}]+\}|\$[a-zA-Z_][a-zA-Z0-9_]*`)

func expandEnv(content string) (string, error) {
var err error
expanded := envReference.ReplaceAllStringFunc(content, func(ref string) string {
if ref == "$$" {
return "$"
}

name := ref[1:]
if ref[1] == '{' {
name = ref[2 : len(ref)-1]
}

value, ok := os.LookupEnv(name)
if !ok && err == nil {
err = fmt.Errorf("environment variable %q is not set", name)
}
return value
})
return expanded, err
}
9 changes: 5 additions & 4 deletions core/conf/properties.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package conf

import (
"fmt"
"os"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -56,10 +55,12 @@ func LoadProperties(filename string, opts ...Option) (Properties, error) {
key := strings.TrimSpace(pair[0])
value := strings.TrimSpace(pair[1])
if opt.env {
raw[key] = os.ExpandEnv(value)
} else {
raw[key] = value
value, err = expandEnv(value)
if err != nil {
return nil, fmt.Errorf("property %q: %w", key, err)
}
}
raw[key] = value
}

return &mapBasedProperties{
Expand Down
Loading