-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.go
More file actions
114 lines (96 loc) · 2.11 KB
/
Copy pathmodule.go
File metadata and controls
114 lines (96 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package config
import (
"log"
"reflect"
"github.com/joho/godotenv"
"github.com/tinh-tinh/tinhtinh/v2/core"
)
const ENV core.Provide = "ConfigEnv"
type Options[E any] struct {
EnvPath string
IgnoreEnvFile bool
// Only for env file
Load func() *E
}
type Param[V any] interface {
string | Options[V]
}
func ForRoot[E any, param Param[E]](params ...param) core.Modules {
return func(module core.Module) core.Module {
var lastValue *E
var err error
if len(params) == 0 {
lastValue, err = New[E]("")
if err != nil {
log.Println("env not found")
}
} else {
var envArrs []E
for _, v := range params {
if reflect.TypeOf(v).Kind() == reflect.String {
val, err := New[E](any(v).(string))
if err != nil {
continue
}
envArrs = append(envArrs, *val)
} else if reflect.TypeOf(v).Kind() == reflect.Struct {
opt := any(v).(Options[E])
err = godotenv.Load(opt.EnvPath)
if err != nil {
continue
}
val := opt.Load()
envArrs = append(envArrs, *val)
}
}
if len(envArrs) > 0 {
value := mergeStruct(envArrs...)
lastValue = &value
}
}
configModule := module.New(core.NewModuleOptions{})
if lastValue == nil {
log.Println("env not found")
return configModule
}
configModule.NewProvider(core.ProviderOptions{
Name: ENV,
Value: lastValue,
})
configModule.Export(ENV)
return configModule
}
}
func Inject[E any](module core.RefProvider) *E {
cfg, ok := module.Ref(ENV).(*E)
if !ok {
return nil
}
return cfg
}
func mergeStruct[T any](input ...T) T {
var result T
resultVal := reflect.ValueOf(&result).Elem()
for _, item := range input {
inputVal := reflect.ValueOf(item)
mergeRecursive(resultVal, inputVal)
}
return result
}
func mergeRecursive(target, source reflect.Value) {
for i := 0; i < target.NumField(); i++ {
tField := target.Field(i)
sField := source.Field(i)
// Handle exported fields only
if !tField.CanSet() {
continue
}
if tField.Kind() == reflect.Struct {
mergeRecursive(tField, sField)
} else {
if !sField.IsZero() {
tField.Set(sField)
}
}
}
}