utils.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. // Package utils provides some common utility methods
  2. package utils
  3. import (
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/rand"
  7. "encoding/hex"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "net"
  12. "strings"
  13. "time"
  14. )
  15. const logSender = "utils"
  16. // IsStringInSlice searches a string in a slice and returns true if the string is found
  17. func IsStringInSlice(obj string, list []string) bool {
  18. for _, v := range list {
  19. if v == obj {
  20. return true
  21. }
  22. }
  23. return false
  24. }
  25. // IsStringPrefixInSlice searches a string prefix in a slice and returns true
  26. // if a matching prefix is found
  27. func IsStringPrefixInSlice(obj string, list []string) bool {
  28. for _, v := range list {
  29. if strings.HasPrefix(obj, v) {
  30. return true
  31. }
  32. }
  33. return false
  34. }
  35. // GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
  36. func GetTimeAsMsSinceEpoch(t time.Time) int64 {
  37. return t.UnixNano() / 1000000
  38. }
  39. // GetTimeFromMsecSinceEpoch return a time struct from a unix timestamp with millisecond precision
  40. func GetTimeFromMsecSinceEpoch(msec int64) time.Time {
  41. return time.Unix(0, msec*1000000)
  42. }
  43. // GetAppVersion returns VersionInfo struct
  44. func GetAppVersion() VersionInfo {
  45. return versionInfo
  46. }
  47. // GetDurationAsString returns a string representation for a time.Duration
  48. func GetDurationAsString(d time.Duration) string {
  49. d = d.Round(time.Second)
  50. h := d / time.Hour
  51. d -= h * time.Hour
  52. m := d / time.Minute
  53. d -= m * time.Minute
  54. s := d / time.Second
  55. if h > 0 {
  56. return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
  57. }
  58. return fmt.Sprintf("%02d:%02d", m, s)
  59. }
  60. // ByteCountSI returns humanized size in SI (decimal) format
  61. func ByteCountSI(b int64) string {
  62. return byteCount(b, 1000)
  63. }
  64. // ByteCountIEC returns humanized size in IEC (binary) format
  65. func ByteCountIEC(b int64) string {
  66. return byteCount(b, 1024)
  67. }
  68. func byteCount(b int64, unit int64) string {
  69. if b < unit {
  70. return fmt.Sprintf("%d B", b)
  71. }
  72. div, exp := unit, 0
  73. for n := b / unit; n >= unit; n /= unit {
  74. div *= unit
  75. exp++
  76. }
  77. if unit == 1000 {
  78. return fmt.Sprintf("%.1f %cB",
  79. float64(b)/float64(div), "KMGTPE"[exp])
  80. }
  81. return fmt.Sprintf("%.1f %ciB",
  82. float64(b)/float64(div), "KMGTPE"[exp])
  83. }
  84. // GetIPFromRemoteAddress returns the IP from the remote address.
  85. // If the given remote address cannot be parsed it will be returned unchanged
  86. func GetIPFromRemoteAddress(remoteAddress string) string {
  87. ip, _, err := net.SplitHostPort(remoteAddress)
  88. if err == nil {
  89. return ip
  90. }
  91. return remoteAddress
  92. }
  93. // NilIfEmpty returns nil if the input string is empty
  94. func NilIfEmpty(s string) *string {
  95. if len(s) == 0 {
  96. return nil
  97. }
  98. return &s
  99. }
  100. // EncryptData encrypts data using the given key
  101. func EncryptData(data string) (string, error) {
  102. var result string
  103. key := make([]byte, 16)
  104. if _, err := io.ReadFull(rand.Reader, key); err != nil {
  105. return result, err
  106. }
  107. keyHex := hex.EncodeToString(key)
  108. block, err := aes.NewCipher([]byte(keyHex))
  109. if err != nil {
  110. return result, err
  111. }
  112. gcm, err := cipher.NewGCM(block)
  113. if err != nil {
  114. return result, err
  115. }
  116. nonce := make([]byte, gcm.NonceSize())
  117. if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
  118. return result, err
  119. }
  120. ciphertext := gcm.Seal(nonce, nonce, []byte(data), nil)
  121. result = fmt.Sprintf("$aes$%s$%x", keyHex, ciphertext)
  122. return result, err
  123. }
  124. // RemoveDecryptionKey returns encrypted data without the decryption key
  125. func RemoveDecryptionKey(encryptData string) string {
  126. vals := strings.Split(encryptData, "$")
  127. if len(vals) == 4 {
  128. return fmt.Sprintf("$%v$%v", vals[1], vals[3])
  129. }
  130. return encryptData
  131. }
  132. // DecryptData decrypts data encrypted using EncryptData
  133. func DecryptData(data string) (string, error) {
  134. var result string
  135. vals := strings.Split(data, "$")
  136. if len(vals) != 4 {
  137. return "", errors.New("data to decrypt is not in the correct format")
  138. }
  139. key := vals[2]
  140. encrypted, err := hex.DecodeString(vals[3])
  141. if err != nil {
  142. return result, err
  143. }
  144. block, err := aes.NewCipher([]byte(key))
  145. if err != nil {
  146. return result, err
  147. }
  148. gcm, err := cipher.NewGCM(block)
  149. if err != nil {
  150. return result, err
  151. }
  152. nonceSize := gcm.NonceSize()
  153. nonce, ciphertext := encrypted[:nonceSize], encrypted[nonceSize:]
  154. plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
  155. if err != nil {
  156. return result, err
  157. }
  158. return string(plaintext), nil
  159. }