functions.go 8.7 KB

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