forked from go-aah/aah
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalpar.go
346 lines (292 loc) · 8.53 KB
/
valpar.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Copyright (c) Jeevanandam M (https://github.com/jeevatkm)
// Source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
// Package valpar provides feature of request value parsing, handling, binding and validating.
package valpar
import (
"encoding/json"
"encoding/xml"
"errors"
"html/template"
"io"
"net/url"
"reflect"
"strconv"
"strings"
"time"
"aahframe.work/ahttp"
"aahframe.work/log"
)
var (
// ErrTypeOrParserIsNil returned when supplied `reflect.Type` or parser is nil to
// the method `AddValueParser`.
ErrTypeOrParserIsNil = errors.New("valpar: type or value parser is nil")
// ErrValueParserIsAlreadyExists returned when given `reflect.Type` is already exists
// in type parser list.
ErrValueParserIsAlreadyExists = errors.New("valpar: value parser is already exists")
// TimeFormats is configured values from aah.conf under `format { ... }`
TimeFormats []string
// StructTagName is used while binding struct fields.
StructTagName string
kindHandlers = map[reflect.Kind]Parser{
reflect.Int: handleTypes,
reflect.Int8: handleTypes,
reflect.Int16: handleTypes,
reflect.Int32: handleTypes,
reflect.Int64: handleTypes,
reflect.Uint: handleTypes,
reflect.Uint8: handleTypes,
reflect.Uint16: handleTypes,
reflect.Uint32: handleTypes,
reflect.Uint64: handleTypes,
reflect.Float32: handleTypes,
reflect.Float64: handleTypes,
reflect.String: handleTypes,
reflect.Bool: handleTypes,
reflect.Slice: handleSlice,
}
typeParsers = map[reflect.Type]Parser{
timeType: handleTypes,
}
timeType = reflect.TypeOf(time.Time{})
)
// Parser interface is used to implement string -> type value parsing. This is
// similar to standard `strconv` package. It deals with reflect value.
type Parser func(key string, typ reflect.Type, params url.Values) (reflect.Value, error)
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Package methods
//______________________________________________________________________________
// AddValueParser method adds given custom value parser for the `reflect.Type`
func AddValueParser(typ reflect.Type, parser Parser) error {
if typ == nil || parser == nil {
return ErrTypeOrParserIsNil
}
if _, found := typeParsers[typ]; found {
return ErrValueParserIsAlreadyExists
}
typeParsers[typ] = parser
return nil
}
// ValueParser method returns the parser based on `reflect.Type` and `reflect.Kind`.
// It returns most of the value parser except Pointer and Struct kind.
// Since Pointer and Struct handled separately.
func ValueParser(typ reflect.Type) (Parser, bool) {
typ, _ = checkPtr(typ)
if parserFn, found := typeParsers[typ]; found {
return parserFn, found
} else if parserFn, found := kindHandlers[typ.Kind()]; found {
return parserFn, found
}
return nil, false
}
// Body method parse the body based on Content-Type.
func Body(contentType string, body io.Reader, typ reflect.Type) (reflect.Value, error) {
var err error
s := reflect.New(typ)
switch contentType {
case ahttp.ContentTypeJSON.Mime, ahttp.ContentTypeJSONText.Mime:
if err = json.NewDecoder(body).Decode(s.Interface()); err != nil {
log.Errorf("json: %s", err)
return s.Elem(), err
}
case ahttp.ContentTypeXML.Mime, ahttp.ContentTypeXMLText.Mime:
if err = xml.NewDecoder(body).Decode(s.Interface()); err != nil {
log.Error(err)
return s.Elem(), err
}
}
return s.Elem(), nil
}
// Struct method parses the value based on Content-Type. It handles JSON and XML.
func Struct(key string, typ reflect.Type, params url.Values) (reflect.Value, error) {
var err error
var isPtr bool
typ, isPtr = checkPtr(typ)
s := reflect.New(typ)
st := s.Type().Elem()
sv := s.Elem()
for idx := 0; idx < st.NumField(); idx++ {
ft := st.Field(idx)
f := sv.Field(idx)
if !f.CanSet() {
continue
}
fname := ft.Tag.Get(StructTagName)
if fname == "-" { // skip the field
continue
}
if len(key) > 0 {
fname = key + "." + fname
}
var v reflect.Value
if vpFn, found := ValueParser(f.Type()); found {
v, err = vpFn(fname, f.Type(), params)
} else if fft, _ := checkPtr(f.Type()); fft.Kind() == reflect.Struct {
v, err = Struct(fname, f.Type(), params)
}
if err != nil {
goto rv
}
if v.IsValid() {
f.Set(v)
}
}
rv:
if isPtr {
return s.Elem().Addr(), err
}
return s.Elem(), err
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Unexported methods
//______________________________________________________________________________
func handleTypes(key string, typ reflect.Type, params url.Values) (reflect.Value, error) {
var err error
var isPtr bool
typ, isPtr = checkPtr(typ)
elem := reflect.New(typ).Elem()
if _, found := params[key]; !found {
goto rv
}
err = parse(params.Get(key), elem)
if err != nil {
log.Errorf("Parameter parse error: %s [type: %s, name: %s, value: %s]", err, typ, key, params.Get(key))
goto rv
}
rv:
if isPtr {
return elem.Addr(), err
}
return elem, err
}
func parse(value string, elem reflect.Value) error {
switch elem.Kind() {
case reflect.String:
return parseString(value, elem)
case reflect.Bool:
return parseBool(value, elem)
case reflect.Float32, reflect.Float64:
return parseFloat(value, elem)
case reflect.Int, reflect.Int64, reflect.Int8, reflect.Int16, reflect.Int32:
return parseInt(value, elem)
case reflect.Uint, reflect.Uint64, reflect.Uint8, reflect.Uint16, reflect.Uint32:
return parseUint(value, elem)
}
if elem.Type() == timeType {
return parseTime(value, elem)
}
return nil
}
func handleSlice(key string, typ reflect.Type, params url.Values) (reflect.Value, error) {
values := params[key]
// check if it's numbered slice, then create slice values from it
if len(values) == 0 {
for k, v := range params {
if strings.HasPrefix(k, key+"[") {
values = append(values, v...)
}
}
}
size := len(values)
slice := reflect.MakeSlice(typ, size, size)
if err := parseSlice(values, slice); err != nil {
log.Errorf("Parameter parse error: %s [type: %s, name: %s, value: %s]", err, typ, key, values)
return slice, err
}
return slice, nil
}
func parseInt(value string, elem reflect.Value) error {
if value == "" {
value = "0"
}
v, err := strconv.ParseInt(value, 10, getBitSize(elem))
if err == nil {
elem.SetInt(v)
}
return err
}
func parseUint(value string, elem reflect.Value) error {
if value == "" {
value = "0"
}
v, err := strconv.ParseUint(value, 10, getBitSize(elem))
if err == nil {
elem.SetUint(v)
}
return err
}
func parseFloat(value string, elem reflect.Value) error {
if value == "" {
value = "0.0"
}
v, err := strconv.ParseFloat(value, getBitSize(elem))
if err == nil {
elem.SetFloat(v)
}
return err
}
func parseBool(value string, elem reflect.Value) error {
if value == "" {
value = "0"
} else if value == "on" || value == "On" {
value = "1"
}
v, err := strconv.ParseBool(value)
if err == nil {
elem.SetBool(v)
}
return err
}
func parseString(value string, elem reflect.Value) error {
// Sanitize it; to prevent XSS attacks
value = template.HTMLEscapeString(value)
elem.SetString(value)
return nil
}
func parseSlice(values []string, elem reflect.Value) (err error) {
for idx := 0; idx < len(values); idx++ {
el := elem.Index(idx)
if el.Kind() == reflect.Ptr {
el.Set(reflect.New(el.Type().Elem()))
err = parse(values[idx], el.Elem())
} else {
err = parse(values[idx], el)
}
if err != nil {
return
}
}
return
}
func parseTime(value string, elem reflect.Value) error {
if len(strings.TrimSpace(value)) == 0 {
return nil
}
for _, format := range TimeFormats {
if t, err := time.Parse(format, value); err == nil {
elem.Set(reflect.ValueOf(t))
return nil
}
}
return errors.New("valpar: unable to parse time as per 'format.time'")
}
func getBitSize(elem reflect.Value) int {
switch elem.Kind() {
case reflect.Int64, reflect.Uint64, reflect.Float64:
return 64
case reflect.Int8, reflect.Uint8:
return 8
case reflect.Int16, reflect.Uint16:
return 16
case reflect.Float32, reflect.Int32, reflect.Uint32:
return 32
default:
return 0 // reflect.Int, reflect.Uint
}
}
func checkPtr(typ reflect.Type) (reflect.Type, bool) {
if typ.Kind() == reflect.Ptr {
return typ.Elem(), true
}
return typ, false
}