git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/validate/converter.go (about) 1 package validate 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 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(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 // ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer. 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 // ToBoolean convert the input string to a boolean. 79 func ToBoolean(str string) (bool, error) { 80 return strconv.ParseBool(str) 81 }