You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

converter.go 1.4KB

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