forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/asaskevich/govalidator/converter.go

107 lines
1.4 KiB
Go
Raw Normal View History

2024-02-18 10:42:21 +00:00
package govalidator
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
)
// ToString convert the input to a string.
2024-02-18 10:42:21 +00:00
func ToString(obj interface{}) string {
2024-02-18 10:42:21 +00:00
res := fmt.Sprintf("%v", obj)
2024-02-18 10:42:21 +00:00
return string(res)
2024-02-18 10:42:21 +00:00
}
// ToJSON convert the input to a valid JSON string
2024-02-18 10:42:21 +00:00
func ToJSON(obj interface{}) (string, error) {
2024-02-18 10:42:21 +00:00
res, err := json.Marshal(obj)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
res = []byte("")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return string(res), err
2024-02-18 10:42:21 +00:00
}
// ToFloat convert the input string to a float, or 0.0 if the input is not a float.
2024-02-18 10:42:21 +00:00
func ToFloat(str string) (float64, error) {
2024-02-18 10:42:21 +00:00
res, err := strconv.ParseFloat(str, 64)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
res = 0.0
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return res, err
2024-02-18 10:42:21 +00:00
}
// ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer.
2024-02-18 10:42:21 +00:00
func ToInt(value interface{}) (res int64, err error) {
2024-02-18 10:42:21 +00:00
val := reflect.ValueOf(value)
switch value.(type) {
2024-02-18 10:42:21 +00:00
case int, int8, int16, int32, int64:
2024-02-18 10:42:21 +00:00
res = val.Int()
2024-02-18 10:42:21 +00:00
case uint, uint8, uint16, uint32, uint64:
2024-02-18 10:42:21 +00:00
res = int64(val.Uint())
2024-02-18 10:42:21 +00:00
case string:
2024-02-18 10:42:21 +00:00
if IsInt(val.String()) {
2024-02-18 10:42:21 +00:00
res, err = strconv.ParseInt(val.String(), 0, 64)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
res = 0
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
err = fmt.Errorf("math: square root of negative number %g", value)
2024-02-18 10:42:21 +00:00
res = 0
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
err = fmt.Errorf("math: square root of negative number %g", value)
2024-02-18 10:42:21 +00:00
res = 0
2024-02-18 10:42:21 +00:00
}
return
2024-02-18 10:42:21 +00:00
}
// ToBoolean convert the input string to a boolean.
2024-02-18 10:42:21 +00:00
func ToBoolean(str string) (bool, error) {
2024-02-18 10:42:21 +00:00
return strconv.ParseBool(str)
2024-02-18 10:42:21 +00:00
}