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