utils.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. package utils
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "math/rand"
  6. "net"
  7. "os"
  8. "reflect"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. //LowerFirst Make a string's first character lowercase
  14. func LowerFirst(s string) string {
  15. isFirst := true
  16. return strings.Map(func(r rune) rune {
  17. if isFirst && r >= 'A' && r <= 'Z' {
  18. r = r + 32
  19. }
  20. isFirst = false
  21. return r
  22. }, s)
  23. }
  24. //UpperFirst Make a string's first character uppercase
  25. func UpperFirst(s string) string {
  26. isFirst := true
  27. return strings.Map(func(r rune) rune {
  28. if isFirst && r >= 'a' && r <= 'z' {
  29. r = r - 32
  30. }
  31. isFirst = false
  32. return r
  33. }, s)
  34. }
  35. //InArray Checks if a value exists in an array
  36. func InArray(needle interface{}, haystack interface{}) bool {
  37. val := reflect.ValueOf(haystack)
  38. switch val.Kind() {
  39. case reflect.Slice, reflect.Array:
  40. for i := 0; i < val.Len(); i++ {
  41. if reflect.DeepEqual(needle, val.Index(i).Interface()) {
  42. return true
  43. }
  44. }
  45. case reflect.Map:
  46. for _, k := range val.MapKeys() {
  47. if reflect.DeepEqual(needle, val.MapIndex(k).Interface()) {
  48. return true
  49. }
  50. }
  51. default:
  52. panic("haystack: haystack type must be slice, array or map")
  53. }
  54. return false
  55. }
  56. //IsEmpty Determine whether a variable is empty
  57. func IsEmpty(val interface{}) bool {
  58. if val == nil {
  59. return true
  60. }
  61. v := reflect.ValueOf(val)
  62. switch v.Kind() {
  63. case reflect.String, reflect.Array:
  64. return v.Len() == 0
  65. case reflect.Map, reflect.Slice:
  66. return v.Len() == 0 || v.IsNil()
  67. case reflect.Bool:
  68. return !v.Bool()
  69. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  70. return v.Int() == 0
  71. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  72. return v.Uint() == 0
  73. case reflect.Float32, reflect.Float64:
  74. return v.Float() == 0
  75. case reflect.Interface, reflect.Ptr:
  76. return v.IsNil()
  77. }
  78. return reflect.DeepEqual(val, reflect.Zero(v.Type()).Interface())
  79. }
  80. //IsNumeric Finds whether a variable is a number or a numeric string
  81. func IsNumeric(val interface{}) bool {
  82. switch val.(type) {
  83. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
  84. return true
  85. case float32, float64, complex64, complex128:
  86. return true
  87. case string:
  88. str := val.(string)
  89. if str == "" {
  90. return false
  91. }
  92. // Trim any whitespace
  93. str = strings.TrimSpace(str)
  94. if str[0] == '-' || str[0] == '+' {
  95. if len(str) == 1 {
  96. return false
  97. }
  98. str = str[1:]
  99. }
  100. // hex
  101. if len(str) > 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X') {
  102. for _, h := range str[2:] {
  103. if !((h >= '0' && h <= '9') || (h >= 'a' && h <= 'f') || (h >= 'A' && h <= 'F')) {
  104. return false
  105. }
  106. }
  107. return true
  108. }
  109. // 0-9, Point, Scientific
  110. p, s, l := 0, 0, len(str)
  111. for i, v := range str {
  112. if v == '.' { // Point
  113. if p > 0 || s > 0 || i+1 == l {
  114. return false
  115. }
  116. p = i
  117. } else if v == 'e' || v == 'E' { // Scientific
  118. if i == 0 || s > 0 || i+1 == l {
  119. return false
  120. }
  121. s = i
  122. } else if v < '0' || v > '9' {
  123. return false
  124. }
  125. }
  126. return true
  127. }
  128. return false
  129. }
  130. //BreakUp break strings
  131. func BreakUp(s string) []string {
  132. length := len(s)
  133. b := make([]byte, length)
  134. ss := make([]string, 0)
  135. var p int
  136. for i := 0; i < length; i++ {
  137. if s[i] >= 'A' && s[i] <= 'Z' {
  138. if p > 0 {
  139. ss = append(ss, string(b[:p]))
  140. }
  141. p = 0
  142. b[p] = s[i] + 32
  143. } else {
  144. b[p] = s[i]
  145. }
  146. p++
  147. }
  148. if p > 0 {
  149. ss = append(ss, string(b[:p]))
  150. }
  151. return ss
  152. }
  153. //Camel2id eg SendMail into send-mail
  154. func Camel2id(s string) string {
  155. return strings.Join(BreakUp(s), "-")
  156. }
  157. //Rand Generate a random integer
  158. func Rand(min, max int) int {
  159. if min > max {
  160. panic("min: min cannot be greater than max")
  161. }
  162. if int31 := 1<<31 - 1; max > int31 {
  163. panic("max: max can not be greater than " + strconv.Itoa(int31))
  164. }
  165. if min == max {
  166. return min
  167. }
  168. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  169. return r.Intn(max+1-min) + min
  170. }
  171. //FileExists Checks whether a file or directory exists
  172. func FileExists(filename string) bool {
  173. if _, err := os.Stat(filename); err != nil && os.IsNotExist(err) {
  174. return false
  175. }
  176. return true
  177. }
  178. //IsDir Tells whether the filename is a directory
  179. func IsDir(filename string) (bool, error) {
  180. fd, err := os.Stat(filename)
  181. if err != nil {
  182. return false, err
  183. }
  184. fm := fd.Mode()
  185. return fm.IsDir(), nil
  186. }
  187. //DirectoryOrCreate checking directory, is not exists will create
  188. func DirectoryOrCreate(dirname string) error {
  189. if fi, err := os.Stat(dirname); err != nil {
  190. if err == os.ErrNotExist {
  191. return os.MkdirAll(dirname, 0755)
  192. } else {
  193. return err
  194. }
  195. } else {
  196. if fi.IsDir() {
  197. return nil
  198. }
  199. return errors.New("file not directory")
  200. }
  201. }
  202. //SimilarText Calculate the similarity between two strings
  203. func SimilarText(first, second string, percent *float64) int {
  204. var similarText func(string, string, int, int) int
  205. similarText = func(str1, str2 string, len1, len2 int) int {
  206. var sum, max int
  207. pos1, pos2 := 0, 0
  208. // Find the longest segment of the same section in two strings
  209. for i := 0; i < len1; i++ {
  210. for j := 0; j < len2; j++ {
  211. for l := 0; (i+l < len1) && (j+l < len2) && (str1[i+l] == str2[j+l]); l++ {
  212. if l+1 > max {
  213. max = l + 1
  214. pos1 = i
  215. pos2 = j
  216. }
  217. }
  218. }
  219. }
  220. if sum = max; sum > 0 {
  221. if pos1 > 0 && pos2 > 0 {
  222. sum += similarText(str1, str2, pos1, pos2)
  223. }
  224. if (pos1+max < len1) && (pos2+max < len2) {
  225. s1 := []byte(str1)
  226. s2 := []byte(str2)
  227. sum += similarText(string(s1[pos1+max:]), string(s2[pos2+max:]), len1-pos1-max, len2-pos2-max)
  228. }
  229. }
  230. return sum
  231. }
  232. l1, l2 := len(first), len(second)
  233. if l1+l2 == 0 {
  234. return 0
  235. }
  236. sim := similarText(first, second, l1, l2)
  237. if percent != nil {
  238. *percent = float64(sim*200) / float64(l1+l2)
  239. }
  240. return sim
  241. }
  242. //IP2long Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer
  243. func IP2long(ipAddress string) uint32 {
  244. ip := net.ParseIP(ipAddress)
  245. if ip == nil {
  246. return 0
  247. }
  248. return binary.BigEndian.Uint32(ip.To4())
  249. }
  250. //Long2IP Converts an long integer address into a string in (IPv4) Internet standard dotted format
  251. func Long2IP(properAddress uint32) string {
  252. ipByte := make([]byte, 4)
  253. binary.BigEndian.PutUint32(ipByte, properAddress)
  254. ip := net.IP(ipByte)
  255. return ip.String()
  256. }