-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.go
49 lines (40 loc) · 1.12 KB
/
functions.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
package form
import (
"errors"
"reflect"
"strconv"
"time"
)
var ErrEmptyInput = errors.New("empty input provided")
type SliceDecodeFunc func([]string) (any, error)
type DecodeFunc func(string) (any, error)
func predefinedDecodeFuncs() map[reflect.Type]DecodeFunc {
return map[reflect.Type]DecodeFunc{
reflect.TypeOf(int(42)): DecodeFuncInt,
reflect.TypeOf(string("")): DecodeFuncString,
reflect.TypeOf(bool(false)): DecodeFuncBool,
reflect.TypeOf(time.Now()): DecodeFuncTime,
}
}
func DecodeFuncInt(value string) (any, error) {
return CheckEmpty(value, strconv.Atoi)
}
func DecodeFuncString(value string) (any, error) {
return CheckEmpty(value, func(v string) (string, error) { return v, nil })
}
func DecodeFuncBool(value string) (any, error) {
return CheckEmpty(value, strconv.ParseBool)
}
func DecodeFuncTime(value string) (any, error) {
return CheckEmpty(value, func(v string) (time.Time, error) {
return time.Parse(time.RFC3339, v)
})
}
func CheckEmpty[T any](value string, f func(string) (T, error)) (t T, e error) {
if len(value) != 0 {
return f(value)
} else {
e = ErrEmptyInput
return
}
}