...
1 package govalidator
2
3 import (
4 "encoding/json"
5 "fmt"
6 "reflect"
7 "strconv"
8 )
9
10
11 func ToString(obj interface{}) string {
12 res := fmt.Sprintf("%v", obj)
13 return res
14 }
15
16
17 func ToJSON(obj interface{}) (string, error) {
18 res, err := json.Marshal(obj)
19 if err != nil {
20 res = []byte("")
21 }
22 return string(res), err
23 }
24
25
26 func ToFloat(value interface{}) (res float64, err error) {
27 val := reflect.ValueOf(value)
28
29 switch value.(type) {
30 case int, int8, int16, int32, int64:
31 res = float64(val.Int())
32 case uint, uint8, uint16, uint32, uint64:
33 res = float64(val.Uint())
34 case float32, float64:
35 res = val.Float()
36 case string:
37 res, err = strconv.ParseFloat(val.String(), 64)
38 if err != nil {
39 res = 0
40 }
41 default:
42 err = fmt.Errorf("ToInt: unknown interface type %T", value)
43 res = 0
44 }
45
46 return
47 }
48
49
50 func ToInt(value interface{}) (res int64, err error) {
51 val := reflect.ValueOf(value)
52
53 switch value.(type) {
54 case int, int8, int16, int32, int64:
55 res = val.Int()
56 case uint, uint8, uint16, uint32, uint64:
57 res = int64(val.Uint())
58 case float32, float64:
59 res = int64(val.Float())
60 case string:
61 if IsInt(val.String()) {
62 res, err = strconv.ParseInt(val.String(), 0, 64)
63 if err != nil {
64 res = 0
65 }
66 } else {
67 err = fmt.Errorf("ToInt: invalid numeric format %g", value)
68 res = 0
69 }
70 default:
71 err = fmt.Errorf("ToInt: unknown interface type %T", value)
72 res = 0
73 }
74
75 return
76 }
77
78
79 func ToBoolean(str string) (bool, error) {
80 return strconv.ParseBool(str)
81 }
82
View as plain text