convert.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package convert
  2. import (
  3. "errors"
  4. "fmt"
  5. "reflect"
  6. "strconv"
  7. )
  8. var (
  9. ErrUnsupported = errors.New("unsupported")
  10. )
  11. func isBytes(v reflect.Value) bool {
  12. if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 {
  13. return true
  14. }
  15. return false
  16. }
  17. func StringValue(v interface{}) (s string, err error) {
  18. refValue := reflect.Indirect(reflect.ValueOf(v))
  19. switch refValue.Kind() {
  20. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  21. s = strconv.FormatInt(refValue.Int(), 10)
  22. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  23. s = strconv.FormatUint(refValue.Uint(), 10)
  24. case reflect.Float32, reflect.Float64:
  25. s = strconv.FormatFloat(refValue.Float(), 'f', -1, 64)
  26. default:
  27. if isBytes(refValue) {
  28. s = string(refValue.Bytes())
  29. } else {
  30. s = fmt.Sprint(refValue.Interface())
  31. }
  32. }
  33. return
  34. }
  35. func IntegerValue(v interface{}) (n int64, err error) {
  36. refValue := reflect.Indirect(reflect.ValueOf(v))
  37. switch refValue.Kind() {
  38. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  39. n = refValue.Int()
  40. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  41. n = int64(refValue.Uint())
  42. case reflect.Float32, reflect.Float64:
  43. n = int64(refValue.Float())
  44. case reflect.String:
  45. n, err = strconv.ParseInt(refValue.String(), 10, 64)
  46. default:
  47. if isBytes(refValue) {
  48. n, err = strconv.ParseInt(string(refValue.Bytes()), 10, 64)
  49. } else {
  50. err = ErrUnsupported
  51. }
  52. }
  53. return
  54. }
  55. func FloatValue(v interface{}) (n float64, err error) {
  56. refValue := reflect.Indirect(reflect.ValueOf(v))
  57. switch refValue.Kind() {
  58. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  59. n = float64(refValue.Int())
  60. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  61. n = float64(refValue.Uint())
  62. case reflect.Float32, reflect.Float64:
  63. n = refValue.Float()
  64. case reflect.String:
  65. n, err = strconv.ParseFloat(refValue.String(), 64)
  66. default:
  67. if isBytes(refValue) {
  68. n, err = strconv.ParseFloat(string(refValue.Bytes()), 64)
  69. } else {
  70. err = ErrUnsupported
  71. }
  72. }
  73. return
  74. }
  75. func MustString(v interface{}) (s string) {
  76. s, _ = StringValue(v)
  77. return
  78. }
  79. func MustInteger(v interface{}) (n int64) {
  80. n, _ = IntegerValue(v)
  81. return
  82. }
  83. func MustFloat(v interface{}) (n float64) {
  84. n, _ = FloatValue(v)
  85. return
  86. }