functions.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. /*
  2. * @description: 常用函数
  3. * @Author: CP
  4. * @Date: 2020-08-21 11:12:56
  5. * @FilePath: \construction_management\comm\functions.go
  6. */
  7. package comm
  8. import (
  9. "bytes"
  10. "crypto/aes"
  11. "crypto/cipher"
  12. "encoding/base64"
  13. "errors"
  14. "math/rand"
  15. "time"
  16. "unicode"
  17. "crypto/md5"
  18. "encoding/binary"
  19. "fmt"
  20. "strconv"
  21. "strings"
  22. "go.mod/conf"
  23. )
  24. // 当前时间的时间戳
  25. func NowUnix() int {
  26. return int(time.Now().In(conf.SysTimeLocation).Unix())
  27. }
  28. // 将unix时间戳格式化为yyyymmdd H:i:s格式字符串
  29. func FormatFromUnixTime(t int64) string {
  30. if t > 0 {
  31. return time.Unix(t, 0).Format(conf.SysTimeform)
  32. } else {
  33. return time.Now().Format(conf.SysTimeform)
  34. }
  35. }
  36. // 将unix时间戳格式化为yyyymmdd格式字符串
  37. func FormatFromUnixTimeShort(t int64) string {
  38. if t > 0 {
  39. return time.Unix(t, 0).Format(conf.SysTimeformShort)
  40. } else {
  41. return time.Now().Format(conf.SysTimeformShort)
  42. }
  43. }
  44. // 将字符串转成时间
  45. func ParseTime(str string) (time.Time, error) {
  46. return time.ParseInLocation(conf.SysTimeform, str, conf.SysTimeLocation)
  47. }
  48. // 得到一个随机数
  49. func Random(max int) int {
  50. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  51. if max < 1 {
  52. return r.Int()
  53. } else {
  54. return r.Intn(max)
  55. }
  56. }
  57. // 对字符串进行签名
  58. func CreateSign(str string) string {
  59. str = string(conf.SignSecret) + str
  60. str1 := fmt.Sprintf("%x", md5.Sum([]byte(str)))
  61. sign := fmt.Sprintf("%x", md5.Sum([]byte(str1)))
  62. return sign
  63. }
  64. // 对一个字符串进行加密
  65. func Encrypt(key, text []byte) ([]byte, error) {
  66. block, err := aes.NewCipher(key)
  67. if err != nil {
  68. return nil, err
  69. }
  70. b := base64.StdEncoding.EncodeToString(text)
  71. ciphertext := make([]byte, aes.BlockSize+len(b))
  72. iv := ciphertext[:aes.BlockSize]
  73. //if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  74. // return nil, err
  75. //}
  76. cfb := cipher.NewCFBEncrypter(block, iv)
  77. cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
  78. return ciphertext, nil
  79. }
  80. // 对一个字符串进行解密
  81. func Decrypt(key, text []byte) ([]byte, error) {
  82. block, err := aes.NewCipher(key)
  83. if err != nil {
  84. return nil, err
  85. }
  86. if len(text) < aes.BlockSize {
  87. return nil, errors.New("ciphertext too short")
  88. }
  89. iv := text[:aes.BlockSize]
  90. text = text[aes.BlockSize:]
  91. cfb := cipher.NewCFBDecrypter(block, iv)
  92. cfb.XORKeyStream(text, text)
  93. data, err := base64.StdEncoding.DecodeString(string(text))
  94. if err != nil {
  95. return nil, err
  96. }
  97. return data, nil
  98. }
  99. // 加密
  100. func AesEncrypt(orig string, key string) string {
  101. // 转成字节数组
  102. origData := []byte(orig)
  103. k := []byte(key)
  104. // 分组秘钥
  105. block, err := aes.NewCipher(k)
  106. if err != nil {
  107. panic(fmt.Sprintf("key 长度必须 16/24/32长度: %s", err.Error()))
  108. }
  109. // 获取秘钥块的长度
  110. blockSize := block.BlockSize()
  111. // 补全码
  112. origData = PKCS7Padding(origData, blockSize)
  113. // 加密模式
  114. blockMode := cipher.NewCBCEncrypter(block, k[:blockSize])
  115. // 创建数组
  116. cryted := make([]byte, len(origData))
  117. // 加密
  118. blockMode.CryptBlocks(cryted, origData)
  119. //使用RawURLEncoding 不要使用StdEncoding
  120. //不要使用StdEncoding 放在url参数中回导致错误
  121. return base64.RawURLEncoding.EncodeToString(cryted)
  122. }
  123. // 解密
  124. func AesDecrypt(cryted string, key string) string {
  125. //使用RawURLEncoding 不要使用StdEncoding
  126. //不要使用StdEncoding 放在url参数中回导致错误
  127. crytedByte, _ := base64.RawURLEncoding.DecodeString(cryted)
  128. k := []byte(key)
  129. // 分组秘钥
  130. block, err := aes.NewCipher(k)
  131. if err != nil {
  132. panic(fmt.Sprintf("key 长度必须 16/24/32长度: %s", err.Error()))
  133. }
  134. // 获取秘钥块的长度
  135. blockSize := block.BlockSize()
  136. // 加密模式
  137. blockMode := cipher.NewCBCDecrypter(block, k[:blockSize])
  138. // 创建数组
  139. orig := make([]byte, len(crytedByte))
  140. // 解密
  141. blockMode.CryptBlocks(orig, crytedByte)
  142. // 去补全码
  143. orig = PKCS7UnPadding(orig)
  144. return string(orig)
  145. }
  146. //补码
  147. func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
  148. padding := blocksize - len(ciphertext)%blocksize
  149. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  150. return append(ciphertext, padtext...)
  151. }
  152. //去码
  153. func PKCS7UnPadding(origData []byte) []byte {
  154. length := len(origData)
  155. unpadding := int(origData[length-1])
  156. return origData[:(length - unpadding)]
  157. }
  158. // addslashes() 函数返回在预定义字符之前添加反斜杠的字符串。
  159. // 预定义字符是:
  160. // 单引号(')
  161. // 双引号(")
  162. // 反斜杠(\)
  163. func Addslashes(str string) string {
  164. tmpRune := []rune{}
  165. strRune := []rune(str)
  166. for _, ch := range strRune {
  167. switch ch {
  168. case []rune{'\\'}[0], []rune{'"'}[0], []rune{'\''}[0]:
  169. tmpRune = append(tmpRune, []rune{'\\'}[0])
  170. tmpRune = append(tmpRune, ch)
  171. default:
  172. tmpRune = append(tmpRune, ch)
  173. }
  174. }
  175. return string(tmpRune)
  176. }
  177. // stripslashes() 函数删除由 addslashes() 函数添加的反斜杠。
  178. func Stripslashes(str string) string {
  179. dstRune := []rune{}
  180. strRune := []rune(str)
  181. strLenth := len(strRune)
  182. for i := 0; i < strLenth; i++ {
  183. if strRune[i] == []rune{'\\'}[0] {
  184. i++
  185. }
  186. dstRune = append(dstRune, strRune[i])
  187. }
  188. return string(dstRune)
  189. }
  190. // 将字符串的IP转化为数字
  191. func Ip4toInt(ip string) int64 {
  192. bits := strings.Split(ip, ".")
  193. if len(bits) == 4 {
  194. b0, _ := strconv.Atoi(bits[0])
  195. b1, _ := strconv.Atoi(bits[1])
  196. b2, _ := strconv.Atoi(bits[2])
  197. b3, _ := strconv.Atoi(bits[3])
  198. var sum int64
  199. sum += int64(b0) << 24
  200. sum += int64(b1) << 16
  201. sum += int64(b2) << 8
  202. sum += int64(b3)
  203. return sum
  204. } else {
  205. return 0
  206. }
  207. }
  208. // 得到当前时间到下一天零点的延时
  209. func NextDayDuration() time.Duration {
  210. year, month, day := time.Now().Add(time.Hour * 24).Date()
  211. next := time.Date(year, month, day, 0, 0, 0, 0, conf.SysTimeLocation)
  212. return next.Sub(time.Now())
  213. }
  214. // 从接口类型安全获取到int64
  215. func GetInt64(i interface{}, d int64) int64 {
  216. if i == nil {
  217. return d
  218. }
  219. switch i.(type) {
  220. case string:
  221. num, err := strconv.Atoi(i.(string))
  222. if err != nil {
  223. return d
  224. } else {
  225. return int64(num)
  226. }
  227. case []byte:
  228. bits := i.([]byte)
  229. if len(bits) == 8 {
  230. return int64(binary.LittleEndian.Uint64(bits))
  231. } else if len(bits) <= 4 {
  232. num, err := strconv.Atoi(string(bits))
  233. if err != nil {
  234. return d
  235. } else {
  236. return int64(num)
  237. }
  238. }
  239. case uint:
  240. return int64(i.(uint))
  241. case uint8:
  242. return int64(i.(uint8))
  243. case uint16:
  244. return int64(i.(uint16))
  245. case uint32:
  246. return int64(i.(uint32))
  247. case uint64:
  248. return int64(i.(uint64))
  249. case int:
  250. return int64(i.(int))
  251. case int8:
  252. return int64(i.(int8))
  253. case int16:
  254. return int64(i.(int16))
  255. case int32:
  256. return int64(i.(int32))
  257. case int64:
  258. return i.(int64)
  259. case float32:
  260. return int64(i.(float32))
  261. case float64:
  262. return int64(i.(float64))
  263. }
  264. return d
  265. }
  266. // 从接口类型安全获取到字符串类型
  267. func GetString(str interface{}, d string) string {
  268. if str == nil {
  269. return d
  270. }
  271. switch str.(type) {
  272. case string:
  273. return str.(string)
  274. case []byte:
  275. return string(str.([]byte))
  276. }
  277. return fmt.Sprintf("%s", str)
  278. }
  279. // 从map中得到指定的key
  280. func GetInt64FromMap(dm map[string]interface{}, key string, dft int64) int64 {
  281. data, ok := dm[key]
  282. if !ok {
  283. return dft
  284. }
  285. return GetInt64(data, dft)
  286. }
  287. // 从map中得到指定的key
  288. func GetInt64FromStringMap(dm map[string]string, key string, dft int64) int64 {
  289. data, ok := dm[key]
  290. if !ok {
  291. return dft
  292. }
  293. return GetInt64(data, dft)
  294. }
  295. // 从map中得到指定的key
  296. func GetStringFromMap(dm map[string]interface{}, key string, dft string) string {
  297. data, ok := dm[key]
  298. if !ok {
  299. return dft
  300. }
  301. return GetString(data, dft)
  302. }
  303. // 从map中得到指定的key
  304. func GetStringFromStringMap(dm map[string]string, key string, dft string) string {
  305. data, ok := dm[key]
  306. if !ok {
  307. return dft
  308. }
  309. return data
  310. }
  311. // 首字母大写
  312. func Ucfirst(str string) string {
  313. for i, v := range str {
  314. return string(unicode.ToUpper(v)) + str[i+1:]
  315. }
  316. return ""
  317. }