Serge Bazanski | cc25bdf | 2018-10-25 14:02:58 +0200 | [diff] [blame] | 1 | package govalidator |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "reflect" |
| 7 | "strconv" |
| 8 | ) |
| 9 | |
| 10 | // ToString convert the input to a string. |
| 11 | func ToString(obj interface{}) string { |
| 12 | res := fmt.Sprintf("%v", obj) |
| 13 | return string(res) |
| 14 | } |
| 15 | |
| 16 | // ToJSON convert the input to a valid JSON string |
| 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 | // ToFloat convert the input string to a float, or 0.0 if the input is not a float. |
| 26 | func ToFloat(str string) (float64, error) { |
| 27 | res, err := strconv.ParseFloat(str, 64) |
| 28 | if err != nil { |
| 29 | res = 0.0 |
| 30 | } |
| 31 | return res, err |
| 32 | } |
| 33 | |
| 34 | // ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer. |
| 35 | func ToInt(value interface{}) (res int64, err error) { |
| 36 | val := reflect.ValueOf(value) |
| 37 | |
| 38 | switch value.(type) { |
| 39 | case int, int8, int16, int32, int64: |
| 40 | res = val.Int() |
| 41 | case uint, uint8, uint16, uint32, uint64: |
| 42 | res = int64(val.Uint()) |
| 43 | case string: |
| 44 | if IsInt(val.String()) { |
| 45 | res, err = strconv.ParseInt(val.String(), 0, 64) |
| 46 | if err != nil { |
| 47 | res = 0 |
| 48 | } |
| 49 | } else { |
| 50 | err = fmt.Errorf("math: square root of negative number %g", value) |
| 51 | res = 0 |
| 52 | } |
| 53 | default: |
| 54 | err = fmt.Errorf("math: square root of negative number %g", value) |
| 55 | res = 0 |
| 56 | } |
| 57 | |
| 58 | return |
| 59 | } |
| 60 | |
| 61 | // ToBoolean convert the input string to a boolean. |
| 62 | func ToBoolean(str string) (bool, error) { |
| 63 | return strconv.ParseBool(str) |
| 64 | } |