utils.go 5.8 KB

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