utils.go 6.4 KB

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