helper.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. package tool
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math"
  9. "math/rand"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "regexp"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "unicode"
  19. )
  20. // GetOrderNumber 获取订单号
  21. func GetOrderNumber() string {
  22. parse, _ := time.Parse(time.DateTime, "2021-04-27 00:00:00")
  23. hours := time.Now().Sub(parse).Hours()
  24. day := math.Floor(hours / 24)
  25. prefix := fmt.Sprintf("%05d", int64(day))
  26. format := time.Now().Format("") + "%0" + strconv.Itoa(10) + "d"
  27. n := math.Pow10(10)
  28. return prefix + fmt.Sprintf(format, rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(int64(n)))
  29. }
  30. // ByteFmt 格式化显示文件大小
  31. func ByteFmt(size int64) string {
  32. var unitArr = []string{"B", "KB", "MB", "GB", "TB", "EB"}
  33. if size == 0 {
  34. return "unknown"
  35. }
  36. fs := float64(size)
  37. p := int(math.Log(fs) / math.Log(1024))
  38. val := fs / math.Pow(1024, float64(p))
  39. _, frac := math.Modf(val)
  40. if frac > 0 {
  41. return fmt.Sprintf("%.1f%s", math.Floor(val*10)/10, unitArr[p])
  42. } else {
  43. return fmt.Sprintf("%d%s", int(val), unitArr[p])
  44. }
  45. }
  46. // UniqueArray 切片唯一值
  47. func UniqueArray[T comparable](array []T) []T {
  48. result := make([]T, 0, len(array))
  49. temp := map[T]struct{}{}
  50. for _, item := range array {
  51. if _, ok := temp[item]; !ok {
  52. temp[item] = struct{}{}
  53. result = append(result, item)
  54. }
  55. }
  56. return result
  57. }
  58. // InArray 是否在切片
  59. func InArray[T comparable](item T, array []T) bool {
  60. for _, s := range array {
  61. if item == s {
  62. return true
  63. }
  64. }
  65. return false
  66. }
  67. func ChunkArray[T comparable](array []T, size int) (ss [][]T) {
  68. if size <= 0 || len(array) <= size {
  69. return [][]T{array}
  70. }
  71. mod := len(array) % size
  72. k := len(array) / size
  73. var end int
  74. if mod == 0 {
  75. end = k
  76. } else {
  77. end = k + 1
  78. }
  79. for i := 0; i < end; i++ {
  80. if i != k {
  81. ss = append(ss, array[i*size:(i+1)*size])
  82. } else {
  83. ss = append(ss, array[i*size:])
  84. }
  85. }
  86. return
  87. }
  88. // IsChinese 判断字符串是否包含中文
  89. func IsChinese(str string) bool {
  90. var count int
  91. for _, v := range str {
  92. if unicode.Is(unicode.Han, v) {
  93. count++
  94. break
  95. }
  96. }
  97. return count > 0
  98. }
  99. // RandInt 随机数
  100. func RandInt(max int) int {
  101. if max <= 0 {
  102. return 0
  103. }
  104. return rand.Intn(max)
  105. }
  106. // FindIPv4 字符串中查找IP4
  107. func FindIPv4(input string) string {
  108. partIp := "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"
  109. must := partIp + "\\." + partIp + "\\." + partIp + "\\." + partIp
  110. matchMe := regexp.MustCompile(must)
  111. return matchMe.FindString(input)
  112. }
  113. // RandString 随机字符串
  114. func RandString(n int) string {
  115. var letterRunes = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  116. b := make([]rune, n)
  117. for i := range b {
  118. b[i] = letterRunes[RandInt(len(letterRunes))]
  119. }
  120. return string(b)
  121. }
  122. // IP4ToInt ip4地址转Int类型
  123. func IP4ToInt(ip net.IP) int {
  124. ipSplit := strings.Split(ip.To4().String(), ".")
  125. var ipInt = 0
  126. var pos uint = 24
  127. for _, ipSeg := range ipSplit {
  128. tempInt, _ := strconv.Atoi(ipSeg)
  129. tempInt = tempInt << pos
  130. ipInt = ipInt | tempInt
  131. pos -= 8
  132. }
  133. return ipInt
  134. }
  135. // IP4IntToString 反序列化Int为IP4地址
  136. func IP4IntToString(ipInt int) string {
  137. ipSplit := make([]string, 4)
  138. var length = len(ipSplit)
  139. buffer := bytes.NewBufferString("")
  140. for i := 0; i < length; i++ {
  141. tempInt := ipInt & 0xFF
  142. ipSplit[length-i-1] = strconv.Itoa(tempInt)
  143. ipInt = ipInt >> 8
  144. }
  145. for i := 0; i < length; i++ {
  146. buffer.WriteString(ipSplit[i])
  147. if i < length-1 {
  148. buffer.WriteString(".")
  149. }
  150. }
  151. return buffer.String()
  152. }
  153. // CompareVersion 比较`x.y.z`类型版本号大小
  154. func CompareVersion(verCurrent, verUpdate string) int {
  155. versionA := strings.Split(verCurrent, ".")
  156. versionB := strings.Split(verUpdate, ".")
  157. for i := len(versionA); i < 4; i++ {
  158. versionA = append(versionA, "0")
  159. }
  160. for i := len(versionB); i < 4; i++ {
  161. versionB = append(versionB, "0")
  162. }
  163. for i := 0; i < 4; i++ {
  164. version1, _ := strconv.Atoi(versionA[i])
  165. version2, _ := strconv.Atoi(versionB[i])
  166. if version1 == version2 {
  167. continue
  168. } else if version1 > version2 {
  169. return 1
  170. } else {
  171. return -1
  172. }
  173. }
  174. return 0
  175. }
  176. // GetLocalIP 获取内网本机ipv4地址
  177. func GetLocalIP() (string, error) {
  178. var address []net.Addr
  179. eth0Interface, err := net.InterfaceByName("eth0")
  180. if err == nil {
  181. address, err = eth0Interface.Addrs()
  182. } else {
  183. address, err = net.InterfaceAddrs()
  184. }
  185. if err != nil {
  186. return "", err
  187. }
  188. for _, addr := range address {
  189. if it, ok := addr.(*net.IPNet); ok && !it.IP.IsLoopback() {
  190. if it.IP.To4() != nil {
  191. return it.IP.String(), nil
  192. }
  193. }
  194. }
  195. return "", err
  196. }
  197. // GetInternetIP 获取外网本机ipv4地址
  198. func GetInternetIP() (string, error) {
  199. resp, err := http.Get("https://api.ipify.org")
  200. if err != nil {
  201. resp, err = http.Get("https://icanhazip.com")
  202. if err != nil {
  203. return "", err
  204. }
  205. }
  206. defer func() {
  207. _ = resp.Body.Close()
  208. }()
  209. s, readErr := io.ReadAll(resp.Body)
  210. if readErr != nil {
  211. return "", readErr
  212. }
  213. return string(s), nil
  214. }
  215. // IsExists 检测指定路径文件或者文件夹是否存在
  216. func IsExists(path string) bool {
  217. _, err := os.Stat(path) //os.Stat获取文件信息
  218. if err != nil {
  219. if os.IsExist(err) {
  220. return true
  221. }
  222. return false
  223. }
  224. return true
  225. }
  226. // CheckWebsiteAddr 检查域名是否正确
  227. func CheckWebsiteAddr(addr string) error {
  228. if 0 == len(addr) {
  229. return errors.New("url is empty")
  230. }
  231. parse, err := url.Parse(addr)
  232. if err != nil {
  233. return err
  234. }
  235. if "http" != parse.Scheme && "https" != parse.Scheme {
  236. return errors.New("url Scheme illegal. err:" + parse.Scheme)
  237. }
  238. re := regexp.MustCompile(`^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$`)
  239. u := strings.Split(parse.Host, ":")
  240. if 2 == len(u) && 0 != len(u[1]) {
  241. result := re.FindAllStringSubmatch(u[0], -1)
  242. if result == nil {
  243. return errors.New("url illegal. err:" + u[0])
  244. }
  245. return nil
  246. }
  247. result := re.FindAllStringSubmatch(parse.Host, -1)
  248. if result == nil {
  249. return errors.New("url illegal. err:" + parse.Host)
  250. }
  251. return nil
  252. }
  253. // LoadKeyValConfig 获取本地`a=c\n`类型文件的键值对
  254. func LoadKeyValConfig(text string) map[string]string {
  255. config := make(map[string]string)
  256. r := bufio.NewReader(bytes.NewBufferString(text))
  257. for {
  258. b, _, err := r.ReadLine()
  259. if err != nil {
  260. if err == io.EOF {
  261. break
  262. }
  263. panic(err)
  264. }
  265. s := strings.TrimSpace(string(b))
  266. index := strings.Index(s, "=")
  267. if index < 0 || strings.HasPrefix(s, "#") {
  268. continue
  269. }
  270. key := strings.TrimSpace(s[:index])
  271. if len(key) == 0 {
  272. continue
  273. }
  274. value := strings.TrimSpace(s[index+1:])
  275. if len(value) == 0 {
  276. continue
  277. }
  278. config[key] = value
  279. }
  280. return config
  281. }
  282. // PortIsUse 判断端口是否占用
  283. func PortIsUse(port int) bool {
  284. _, tcpError := net.DialTimeout("tcp", fmt.Sprintf(":%d", port), time.Millisecond*50)
  285. udpAddr, _ := net.ResolveUDPAddr("udp4", fmt.Sprintf(":%d", port))
  286. udpConn, udpError := net.ListenUDP("udp", udpAddr)
  287. if udpConn != nil {
  288. defer func() {
  289. _ = udpConn.Close()
  290. }()
  291. }
  292. return tcpError == nil || udpError != nil
  293. }