helper.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. // IsChinese 判断字符串是否包含中文
  68. func IsChinese(str string) bool {
  69. var count int
  70. for _, v := range str {
  71. if unicode.Is(unicode.Han, v) {
  72. count++
  73. break
  74. }
  75. }
  76. return count > 0
  77. }
  78. // RandInt 随机数
  79. func RandInt(max int) int {
  80. if max <= 0 {
  81. return 0
  82. }
  83. return rand.Intn(max)
  84. }
  85. // FindIPv4 字符串中查找IP4
  86. func FindIPv4(input string) string {
  87. partIp := "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"
  88. must := partIp + "\\." + partIp + "\\." + partIp + "\\." + partIp
  89. matchMe := regexp.MustCompile(must)
  90. return matchMe.FindString(input)
  91. }
  92. // RandString 随机字符串
  93. func RandString(n int) string {
  94. var letterRunes = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  95. b := make([]rune, n)
  96. for i := range b {
  97. b[i] = letterRunes[RandInt(len(letterRunes))]
  98. }
  99. return string(b)
  100. }
  101. // IP4ToInt ip4地址转Int类型
  102. func IP4ToInt(ip net.IP) int {
  103. ipSplit := strings.Split(ip.To4().String(), ".")
  104. var ipInt = 0
  105. var pos uint = 24
  106. for _, ipSeg := range ipSplit {
  107. tempInt, _ := strconv.Atoi(ipSeg)
  108. tempInt = tempInt << pos
  109. ipInt = ipInt | tempInt
  110. pos -= 8
  111. }
  112. return ipInt
  113. }
  114. // IP4IntToString 反序列化Int为IP4地址
  115. func IP4IntToString(ipInt int) string {
  116. ipSplit := make([]string, 4)
  117. var length = len(ipSplit)
  118. buffer := bytes.NewBufferString("")
  119. for i := 0; i < length; i++ {
  120. tempInt := ipInt & 0xFF
  121. ipSplit[length-i-1] = strconv.Itoa(tempInt)
  122. ipInt = ipInt >> 8
  123. }
  124. for i := 0; i < length; i++ {
  125. buffer.WriteString(ipSplit[i])
  126. if i < length-1 {
  127. buffer.WriteString(".")
  128. }
  129. }
  130. return buffer.String()
  131. }
  132. // CompareVersion 比较`x.y.z`类型版本号大小
  133. func CompareVersion(verCurrent, verUpdate string) int {
  134. versionA := strings.Split(verCurrent, ".")
  135. versionB := strings.Split(verUpdate, ".")
  136. for i := len(versionA); i < 4; i++ {
  137. versionA = append(versionA, "0")
  138. }
  139. for i := len(versionB); i < 4; i++ {
  140. versionB = append(versionB, "0")
  141. }
  142. for i := 0; i < 4; i++ {
  143. version1, _ := strconv.Atoi(versionA[i])
  144. version2, _ := strconv.Atoi(versionB[i])
  145. if version1 == version2 {
  146. continue
  147. } else if version1 > version2 {
  148. return 1
  149. } else {
  150. return -1
  151. }
  152. }
  153. return 0
  154. }
  155. // GetLocalIP 获取内网本机ipv4地址
  156. func GetLocalIP() (string, error) {
  157. var address []net.Addr
  158. eth0Interface, err := net.InterfaceByName("eth0")
  159. if err == nil {
  160. address, err = eth0Interface.Addrs()
  161. } else {
  162. address, err = net.InterfaceAddrs()
  163. }
  164. if err != nil {
  165. return "", err
  166. }
  167. for _, addr := range address {
  168. if it, ok := addr.(*net.IPNet); ok && !it.IP.IsLoopback() {
  169. if it.IP.To4() != nil {
  170. return it.IP.String(), nil
  171. }
  172. }
  173. }
  174. return "", err
  175. }
  176. // GetInternetIP 获取外网本机ipv4地址
  177. func GetInternetIP() (string, error) {
  178. resp, err := http.Get("https://api.ipify.org")
  179. if err != nil {
  180. resp, err = http.Get("https://icanhazip.com")
  181. if err != nil {
  182. return "", err
  183. }
  184. }
  185. defer func() {
  186. _ = resp.Body.Close()
  187. }()
  188. s, readErr := io.ReadAll(resp.Body)
  189. if readErr != nil {
  190. return "", readErr
  191. }
  192. return string(s), nil
  193. }
  194. // IsExists 检测指定路径文件或者文件夹是否存在
  195. func IsExists(path string) bool {
  196. _, err := os.Stat(path) //os.Stat获取文件信息
  197. if err != nil {
  198. if os.IsExist(err) {
  199. return true
  200. }
  201. return false
  202. }
  203. return true
  204. }
  205. // CheckWebsiteAddr 检查域名是否正确
  206. func CheckWebsiteAddr(addr string) error {
  207. if 0 == len(addr) {
  208. return errors.New("url is empty")
  209. }
  210. parse, err := url.Parse(addr)
  211. if err != nil {
  212. return err
  213. }
  214. if "http" != parse.Scheme && "https" != parse.Scheme {
  215. return errors.New("url Scheme illegal. err:" + parse.Scheme)
  216. }
  217. 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])$`)
  218. u := strings.Split(parse.Host, ":")
  219. if 2 == len(u) && 0 != len(u[1]) {
  220. result := re.FindAllStringSubmatch(u[0], -1)
  221. if result == nil {
  222. return errors.New("url illegal. err:" + u[0])
  223. }
  224. return nil
  225. }
  226. result := re.FindAllStringSubmatch(parse.Host, -1)
  227. if result == nil {
  228. return errors.New("url illegal. err:" + parse.Host)
  229. }
  230. return nil
  231. }
  232. // LoadKeyValConfig 获取本地`a=c\n`类型文件的键值对
  233. func LoadKeyValConfig(text string) map[string]string {
  234. config := make(map[string]string)
  235. r := bufio.NewReader(bytes.NewBufferString(text))
  236. for {
  237. b, _, err := r.ReadLine()
  238. if err != nil {
  239. if err == io.EOF {
  240. break
  241. }
  242. panic(err)
  243. }
  244. s := strings.TrimSpace(string(b))
  245. index := strings.Index(s, "=")
  246. if index < 0 || strings.HasPrefix(s, "#") {
  247. continue
  248. }
  249. key := strings.TrimSpace(s[:index])
  250. if len(key) == 0 {
  251. continue
  252. }
  253. value := strings.TrimSpace(s[index+1:])
  254. if len(value) == 0 {
  255. continue
  256. }
  257. config[key] = value
  258. }
  259. return config
  260. }
  261. // PortIsUse 判断端口是否占用
  262. func PortIsUse(port int) bool {
  263. _, tcpError := net.DialTimeout("tcp", fmt.Sprintf(":%d", port), time.Millisecond*50)
  264. udpAddr, _ := net.ResolveUDPAddr("udp4", fmt.Sprintf(":%d", port))
  265. udpConn, udpError := net.ListenUDP("udp", udpAddr)
  266. if udpConn != nil {
  267. defer func() {
  268. _ = udpConn.Close()
  269. }()
  270. }
  271. return tcpError == nil || udpError != nil
  272. }