-
Notifications
You must be signed in to change notification settings - Fork 522
/
config_util.go
202 lines (189 loc) · 6.24 KB
/
config_util.go
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package helper
import (
"fmt"
"reflect"
"github.com/go-playground/validator/v10"
"github.com/mitchellh/mapstructure"
"github.com/spf13/viper"
)
// DecodeStruct validates `input` struct with `validator` and set it into viper
// `tag` represent the fields when setting config, and the fields with `tag` shall prevail.
// `input` must be a pointer
func DecodeStruct(output *viper.Viper, input interface{}, data map[string]interface{}, tag string) error {
// update fields from request body
err := mapstructure.Decode(data, input)
if err != nil {
return err
}
// validate fields with `validate` tag
vld := validator.New()
err = vld.Struct(input)
if err != nil {
return err
}
err = validator.New().Struct(input)
if err != nil {
return err
}
vf := reflect.ValueOf(input)
if vf.Kind() != reflect.Ptr {
return fmt.Errorf("input %v is not a pointer", input)
}
tf := reflect.Indirect(vf).Type()
fieldTags := make([]string, 0)
fieldNames := make([]string, 0)
fieldTypes := make([]reflect.Type, 0)
walkFields(tf, &fieldNames, &fieldTypes, &fieldTags, tag)
length := len(fieldNames)
for i := 0; i < length; i++ {
fieldName := fieldNames[i]
fieldType := fieldTypes[i]
fieldTag := fieldTags[i]
// Check if the first letter is uppercase (indicates a public element, accessible)
ascii := rune(fieldName[0])
if int(ascii) < int('A') || int(ascii) > int('Z') {
continue
}
// View their tags in order to filter out members who don't have a valid tag set
if fieldTag == "" {
continue
}
vfField := vf.Elem().FieldByName(fieldName)
switch fieldType.Kind() {
case reflect.String:
output.Set(fieldTag, vfField.String())
case reflect.Int, reflect.Int64:
output.Set(fieldTag, vfField.Int())
case reflect.Float64, reflect.Float32:
output.Set(fieldTag, vfField.Float())
case reflect.Bool:
output.Set(fieldTag, vfField.Bool())
case reflect.Slice:
elemType := vfField.Type().Elem().Kind()
switch elemType {
case reflect.String:
output.Set(fieldTag, vfField.Interface().([]string))
case reflect.Int:
output.Set(fieldTag, vfField.Interface().([]int))
}
case reflect.Map:
keyType := vfField.Type().Key().Kind()
elemType := vfField.Type().Elem().Kind()
if keyType == reflect.String {
switch elemType {
case reflect.String:
output.Set(fieldTag, vfField.Interface().(map[string]string))
case reflect.Interface:
output.Set(fieldTag, vfField.Interface().(map[string]interface{}))
}
}
default:
}
}
return nil
}
// EncodeStruct encodes struct from viper
// `tag` represent the fields when setting config, and the fields with `tag` shall prevail.
// `object` must be a pointer
func EncodeStruct(input *viper.Viper, output interface{}, tag string) error {
vf := reflect.ValueOf(output)
if vf.Kind() != reflect.Ptr {
return fmt.Errorf("output %v is not a pointer", output)
}
tf := reflect.Indirect(vf).Type()
fieldTags := make([]string, 0)
fieldNames := make([]string, 0)
fieldTypes := make([]reflect.Type, 0)
walkFields(tf, &fieldNames, &fieldTypes, &fieldTags, tag)
length := len(fieldNames)
for i := 0; i < length; i++ {
fieldName := fieldNames[i]
fieldType := fieldTypes[i]
fieldTag := fieldTags[i]
// Check if the first letter is uppercase (indicates a public element, accessible)
ascii := rune(fieldName[0])
if int(ascii) < int('A') || int(ascii) > int('Z') {
continue
}
// View their tags in order to filter out members who don't have a valid tag set
if fieldTag == "" {
continue
}
vfField := vf.Elem().FieldByName(fieldName)
switch fieldType.Kind() {
case reflect.String:
vfField.SetString(input.GetString(fieldTag))
case reflect.Int, reflect.Int64:
vfField.SetInt(input.GetInt64(fieldTag))
case reflect.Float64:
vfField.SetFloat(input.GetFloat64(fieldTag))
case reflect.Bool:
vfField.SetBool(input.GetBool(fieldTag))
case reflect.Slice:
elem := vfField.Type().Elem()
switch elem.Kind() {
case reflect.String:
value := input.GetStringSlice(fieldTag)
stringSlice := reflect.MakeSlice(reflect.SliceOf(elem), 0, len(value))
for _, item := range value {
stringSlice = reflect.Append(stringSlice, reflect.ValueOf(item))
}
vfField.Set(stringSlice)
case reflect.Int:
value := input.GetIntSlice(fieldTag)
intSlice := reflect.MakeSlice(reflect.SliceOf(elem), 0, len(value))
for _, item := range value {
intSlice = reflect.Append(intSlice, reflect.ValueOf(item))
}
vfField.Set(intSlice)
}
case reflect.Map:
key := vfField.Type().Key()
elem := vfField.Type().Elem()
if key.Kind() == reflect.String {
mapType := reflect.MapOf(key, elem)
data := reflect.MakeMap(mapType)
switch elem.Kind() {
case reflect.String:
for k, value := range input.GetStringMapString(fieldTag) {
data.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(value))
}
case reflect.Interface:
for k, value := range input.GetStringMap(fieldTag) {
data.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(value))
}
}
vfField.Set(data)
}
default:
}
}
return nil
}
func walkFields(t reflect.Type, fieldNames *[]string, fieldTypes *[]reflect.Type, fieldTags *[]string, tag string) {
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.Type.Kind() == reflect.Struct {
walkFields(field.Type, fieldNames, fieldTypes, fieldTags, tag)
} else {
fieldTag := field.Tag.Get(tag)
*fieldNames = append(*fieldNames, field.Name)
*fieldTypes = append(*fieldTypes, field.Type)
*fieldTags = append(*fieldTags, fieldTag)
}
}
}