utils.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package common
  2. import (
  3. "bytes"
  4. "confrontation-training/constant"
  5. "encoding/binary"
  6. "encoding/hex"
  7. "fmt"
  8. "github.com/google/uuid"
  9. "log"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. )
  14. // GenerateUUID 生成UUID
  15. //Deprecated
  16. func GenerateUUID() string {
  17. UUID, err := uuid.NewRandom()
  18. if err != nil {
  19. _ = fmt.Sprintf("UUID generate err:%s", err.Error())
  20. return ""
  21. }
  22. return strings.Replace(UUID.String(), "-", "", -1)
  23. }
  24. // CheckFile 检查文件扩展名
  25. //Deprecated
  26. func CheckFile(fileName string) string {
  27. fileNames := []string{"json", "txt", "wav", "npy", "xlsx", "xls"}
  28. for _, temp := range fileNames {
  29. if strings.HasSuffix(strings.ToLower(fileName), temp) {
  30. return temp
  31. }
  32. }
  33. return ""
  34. }
  35. // GetCurrentAbPathByExecutable 获取当前执行程序所在的绝对路径
  36. //Deprecated
  37. func GetCurrentAbPathByExecutable() string {
  38. exePath, err := os.Executable()
  39. if err != nil {
  40. log.Fatal(err)
  41. }
  42. res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
  43. return res
  44. }
  45. func Int2Bytes(i int) [4]byte {
  46. var result [4]byte
  47. result[0] = byte(i >> 24 & 0xFF)
  48. result[1] = byte(i >> 16 & 0xFF)
  49. result[2] = byte(i >> 8 & 0xFF)
  50. result[3] = byte(i & 0xFF)
  51. return result
  52. }
  53. func Bytes2HexStr(bytes [4]byte) string {
  54. var result string
  55. for _, value := range bytes {
  56. if &value == nil {
  57. result = ""
  58. break
  59. }
  60. result = fmt.Sprint(result, value&0xFF)
  61. }
  62. return result
  63. }
  64. // GenerateHexStringCmdPlaceHolder 生成名称占位符
  65. func GenerateHexStringCmdPlaceHolder(length int) string {
  66. if length <= 0 {
  67. return ""
  68. }
  69. if length%2 != 0 {
  70. fmt.Println("占位符个数为奇数")
  71. }
  72. var sb strings.Builder
  73. for i := 0; i < length; i++ {
  74. sb.WriteString(constant.DefaultPlaceHolder)
  75. }
  76. return sb.String()
  77. }
  78. func Int2Byte(i int64) string {
  79. bytesBuffer := bytes.NewBuffer([]byte{})
  80. err := binary.Write(bytesBuffer, binary.BigEndian, i)
  81. if err != nil {
  82. fmt.Println("数据转换异常:" + err.Error())
  83. return ""
  84. }
  85. return hex.EncodeToString(bytesBuffer.Bytes())
  86. }