is.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package util
  4. import (
  5. "os"
  6. "reflect"
  7. "strconv"
  8. "time"
  9. )
  10. // IsNumber 判断一个值是否可转换为数值。不支持全角数值的判断。
  11. func IsNumber(val interface{}) bool {
  12. switch v := val.(type) {
  13. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64:
  14. return true
  15. case []byte:
  16. _, err := strconv.ParseFloat(string(v), 32)
  17. return err == nil
  18. case string:
  19. _, err := strconv.ParseFloat(v, 32)
  20. return err == nil
  21. case []rune:
  22. _, err := strconv.ParseFloat(string(v), 32)
  23. return err == nil
  24. default:
  25. return false
  26. }
  27. }
  28. // IsNil 是否为 nil,有类型但无具体值的也将返回 true,
  29. // 当特定类型的变量,已经声明,但还未赋值时,也将返回 true
  30. func IsNil(val interface{}) bool {
  31. if nil == val {
  32. return true
  33. }
  34. v := reflect.ValueOf(val)
  35. k := v.Kind()
  36. return k >= reflect.Chan && k <= reflect.Slice && v.IsNil()
  37. }
  38. // Empty 是否为空,若是容器类型,长度为 0 也将返回 true,
  39. // 但是 []string{""}空数组里套一个空字符串,不会被判断为空。
  40. func IsEmpty(val interface{}) bool {
  41. if val == nil {
  42. return true
  43. }
  44. switch v := val.(type) {
  45. case bool:
  46. return !v
  47. case int:
  48. return 0 == v
  49. case int8:
  50. return 0 == v
  51. case int16:
  52. return 0 == v
  53. case int32:
  54. return 0 == v
  55. case int64:
  56. return 0 == v
  57. case uint:
  58. return 0 == v
  59. case uint8:
  60. return 0 == v
  61. case uint16:
  62. return 0 == v
  63. case uint32:
  64. return 0 == v
  65. case uint64:
  66. return 0 == v
  67. case string:
  68. return len(v) == 0
  69. case float32:
  70. return 0 == v
  71. case float64:
  72. return 0 == v
  73. case time.Time:
  74. return v.IsZero()
  75. case *time.Time:
  76. return v.IsZero()
  77. }
  78. // 符合 Nil 条件的,都为 Empty
  79. if IsNil(val) {
  80. return true
  81. }
  82. // 长度为 0 的数组也是 empty
  83. v := reflect.ValueOf(val)
  84. switch v.Kind() {
  85. case reflect.Slice, reflect.Map, reflect.Chan:
  86. return 0 == v.Len()
  87. }
  88. return false
  89. }
  90. // IsExistFile 判断文件或是文件夹是否存在
  91. func IsFileExist(filename string) bool {
  92. _, err := os.Stat(filename)
  93. return err == nil || os.IsExist(err)
  94. }