functions.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 MakeFolderContract(Data []*viewmodels.FolderContract, node *viewmodels.FolderContract) { //参数为父节点,添加父节点的子节点指针切片
  44. childs, _ := HaveChildContract(Data, node) //判断节点是否有子节点并返回
  45. if childs != nil {
  46. // 子节点总数
  47. Total := len(childs)
  48. node.ChildsTotal = Total
  49. // 标记最后一个元素
  50. end := Total - 1
  51. childs[end].IsEnd = true
  52. // 往父节点添加子节点
  53. node.Children = append(node.Children, childs[0:]...) //添加子节点
  54. for _, v := range childs { //查询子节点的子节点,并添加到子节点
  55. _, has := HaveChildContract(Data, v)
  56. if has {
  57. // 递归添加节点
  58. MakeFolderContract(Data, v)
  59. }
  60. // 目录下是否包含标段
  61. if v.Isfolder == 0 {
  62. node.IsBid = true
  63. } else {
  64. node.HasFolder = true
  65. }
  66. }
  67. }
  68. }
  69. // 是否有子树
  70. func HaveChildContract(Data []*viewmodels.FolderContract, node *viewmodels.FolderContract) (child []*viewmodels.FolderContract, yes bool) {
  71. for _, v := range Data {
  72. if v.ParentId == node.Id {
  73. child = append(child, v)
  74. }
  75. }
  76. if child != nil {
  77. yes = true
  78. }
  79. return
  80. }
  81. // 创建合同项目节树
  82. func MakeSectionContract(Data []*viewmodels.TreeSectionContract, node *viewmodels.TreeSectionContract) { //参数为父节点,添加父节点的子节点指针切片
  83. childs, _ := haveChildSectionContract(Data, node) //判断节点是否有子节点并返回
  84. if childs != nil {
  85. // 往父节点添加子节点
  86. // 孩子们从小到大排序
  87. if len(childs) != 0 {
  88. sectionSelectionSort(childs)
  89. childs[0].ElderBrother = false
  90. childs[len(childs)-1].IsEnd = true
  91. }
  92. node.Children = append(node.Children, childs[0:]...) //添加子节点
  93. for _, v := range childs { //查询子节点的子节点,并添加到子节点
  94. _, has := haveChildSectionContract(Data, v)
  95. if has {
  96. // 递归添加节点
  97. MakeSectionContract(Data, v)
  98. }
  99. }
  100. }
  101. }
  102. // 合同项目节孩子排序
  103. func sectionSelectionSort(child []*viewmodels.TreeSectionContract) {
  104. for i := 0; i < len(child); i++ {
  105. minIndex := i
  106. // 查找最小值
  107. for j := i; j < len(child); j++ {
  108. if child[j].Serial < child[minIndex].Serial {
  109. minIndex = j
  110. }
  111. }
  112. swapContract(child, i, minIndex)
  113. }
  114. }
  115. func swapContract(child []*viewmodels.TreeSectionContract, i int, minIndex int) {
  116. t := child[i]
  117. child[i] = child[minIndex]
  118. child[minIndex] = t
  119. }
  120. // 是否有子树
  121. func haveChildSectionContract(Data []*viewmodels.TreeSectionContract, node *viewmodels.TreeSectionContract) (child []*viewmodels.TreeSectionContract, yes bool) {
  122. for _, v := range Data {
  123. if v.ParentId == node.Id {
  124. child = append(child, v)
  125. }
  126. }
  127. if child != nil {
  128. yes = true
  129. }
  130. return
  131. }
  132. // 当前时间的时间戳
  133. func NowUnix() int {
  134. return int(time.Now().In(conf.SysTimeLocation).Unix())
  135. }
  136. // 将unix时间戳格式化为yyyymmdd H:i:s格式字符串
  137. func FormatFromUnixTime(t int64) string {
  138. if t > 0 {
  139. return time.Unix(t, 0).Format(conf.SysTimeform)
  140. } else {
  141. return time.Now().Format(conf.SysTimeform)
  142. }
  143. }
  144. // 将unix时间戳格式化为yyyymmdd格式字符串
  145. func FormatFromUnixTimeShort(t int64) string {
  146. if t > 0 {
  147. return time.Unix(t, 0).Format(conf.SysTimeformShort)
  148. } else {
  149. return time.Now().Format(conf.SysTimeformShort)
  150. }
  151. }
  152. // 将字符串转成时间
  153. func ParseTime(str string) (time.Time, error) {
  154. return time.ParseInLocation(conf.SysTimeform, str, conf.SysTimeLocation)
  155. }
  156. // 得到一个随机数
  157. func Random(max int) int {
  158. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  159. if max < 1 {
  160. return r.Int()
  161. } else {
  162. return r.Intn(max)
  163. }
  164. }
  165. // 加密密码
  166. func CreatePasswordSign(password string, account string) string {
  167. str := string(conf.SignSecret) + password + account
  168. str1 := fmt.Sprintf("%x", md5.Sum([]byte(str)))
  169. sign := fmt.Sprintf("%x", md5.Sum([]byte(str1)))
  170. return sign
  171. }
  172. // 对字符串进行签名
  173. func CreateSign(str string) string {
  174. str = string(conf.SignSecret) + str
  175. str1 := fmt.Sprintf("%x", md5.Sum([]byte(str)))
  176. sign := fmt.Sprintf("%x", md5.Sum([]byte(str1)))
  177. return sign
  178. }
  179. // 对一个字符串进行加密
  180. func Encrypt(key, text []byte) (string, error) {
  181. block, err := aes.NewCipher(key)
  182. if err != nil {
  183. return "", err
  184. }
  185. b := base64.StdEncoding.EncodeToString(text)
  186. ciphertext := make([]byte, aes.BlockSize+len(b))
  187. iv := ciphertext[:aes.BlockSize]
  188. //if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  189. // return nil, err
  190. //}
  191. cfb := cipher.NewCFBEncrypter(block, iv)
  192. cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
  193. return base64.RawURLEncoding.EncodeToString(ciphertext), nil
  194. }
  195. // 对一个字符串进行解密
  196. func Decrypt(key, text []byte) ([]byte, error) {
  197. block, err := aes.NewCipher(key)
  198. if err != nil {
  199. return nil, err
  200. }
  201. if len(text) < aes.BlockSize {
  202. return nil, errors.New("ciphertext too short")
  203. }
  204. iv := text[:aes.BlockSize]
  205. text = text[aes.BlockSize:]
  206. cfb := cipher.NewCFBDecrypter(block, iv)
  207. cfb.XORKeyStream(text, text)
  208. data, err := base64.StdEncoding.DecodeString(string(text))
  209. if err != nil {
  210. return nil, err
  211. }
  212. return data, nil
  213. }
  214. // 加密
  215. func AesEncrypt(orig string, key string) (string, error) {
  216. // 转成字节数组
  217. origData := []byte(orig)
  218. k := []byte(key)
  219. // 分组秘钥
  220. block, err := aes.NewCipher(k)
  221. if err != nil {
  222. return "", err
  223. }
  224. // 获取秘钥块的长度
  225. blockSize := block.BlockSize()
  226. // 补全码
  227. origData = PKCS7Padding(origData, blockSize)
  228. // 加密模式
  229. blockMode := cipher.NewCBCEncrypter(block, k[:blockSize])
  230. // 创建数组
  231. cryted := make([]byte, len(origData))
  232. // 加密
  233. blockMode.CryptBlocks(cryted, origData)
  234. //使用RawURLEncoding 不要使用StdEncoding
  235. //不要使用StdEncoding 放在url参数中回导致错误
  236. return base64.RawURLEncoding.EncodeToString(cryted), nil
  237. }
  238. // 解密
  239. func AesDecrypt(cryted string, key string) (string, error) {
  240. //使用RawURLEncoding 不要使用StdEncoding
  241. //不要使用StdEncoding 放在url参数中回导致错误
  242. crytedByte, err := base64.RawURLEncoding.DecodeString(cryted)
  243. if err != nil {
  244. return "", err
  245. }
  246. k := []byte(key)
  247. // 分组秘钥
  248. block, err := aes.NewCipher(k)
  249. if err != nil {
  250. return "", err
  251. }
  252. // 获取秘钥块的长度
  253. blockSize := block.BlockSize()
  254. // 加密模式
  255. blockMode := cipher.NewCBCDecrypter(block, k[:blockSize])
  256. // 创建数组
  257. orig := make([]byte, len(crytedByte))
  258. // 解密--传入不正确的字符时会报错-TODO 需捕获
  259. blockMode.CryptBlocks(orig, crytedByte)
  260. // 去补全码
  261. orig = PKCS7UnPadding(orig)
  262. return string(orig), nil
  263. }
  264. //补码
  265. func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
  266. padding := blocksize - len(ciphertext)%blocksize
  267. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  268. return append(ciphertext, padtext...)
  269. }
  270. //去码
  271. func PKCS7UnPadding(origData []byte) []byte {
  272. length := len(origData)
  273. unpadding := int(origData[length-1])
  274. return origData[:(length - unpadding)]
  275. }
  276. // addslashes() 函数返回在预定义字符之前添加反斜杠的字符串。
  277. // 预定义字符是:
  278. // 单引号(')
  279. // 双引号(")
  280. // 反斜杠(\)
  281. func Addslashes(str string) string {
  282. tmpRune := []rune{}
  283. strRune := []rune(str)
  284. for _, ch := range strRune {
  285. switch ch {
  286. case []rune{'\\'}[0], []rune{'"'}[0], []rune{'\''}[0]:
  287. tmpRune = append(tmpRune, []rune{'\\'}[0])
  288. tmpRune = append(tmpRune, ch)
  289. default:
  290. tmpRune = append(tmpRune, ch)
  291. }
  292. }
  293. return string(tmpRune)
  294. }
  295. // stripslashes() 函数删除由 addslashes() 函数添加的反斜杠。
  296. func Stripslashes(str string) string {
  297. dstRune := []rune{}
  298. strRune := []rune(str)
  299. strLenth := len(strRune)
  300. for i := 0; i < strLenth; i++ {
  301. if strRune[i] == []rune{'\\'}[0] {
  302. i++
  303. }
  304. dstRune = append(dstRune, strRune[i])
  305. }
  306. return string(dstRune)
  307. }
  308. // 将字符串的IP转化为数字
  309. func Ip4toInt(ip string) int64 {
  310. bits := strings.Split(ip, ".")
  311. if len(bits) == 4 {
  312. b0, _ := strconv.Atoi(bits[0])
  313. b1, _ := strconv.Atoi(bits[1])
  314. b2, _ := strconv.Atoi(bits[2])
  315. b3, _ := strconv.Atoi(bits[3])
  316. var sum int64
  317. sum += int64(b0) << 24
  318. sum += int64(b1) << 16
  319. sum += int64(b2) << 8
  320. sum += int64(b3)
  321. return sum
  322. } else {
  323. return 0
  324. }
  325. }
  326. // 得到当前时间到下一天零点的延时
  327. func NextDayDuration() time.Duration {
  328. year, month, day := time.Now().Add(time.Hour * 24).Date()
  329. next := time.Date(year, month, day, 0, 0, 0, 0, conf.SysTimeLocation)
  330. return next.Sub(time.Now())
  331. }
  332. // 从接口类型安全获取到int64
  333. func GetInt64(i interface{}, d int64) int64 {
  334. if i == nil {
  335. return d
  336. }
  337. switch i.(type) {
  338. case string:
  339. num, err := strconv.Atoi(i.(string))
  340. if err != nil {
  341. return d
  342. } else {
  343. return int64(num)
  344. }
  345. case []byte:
  346. bits := i.([]byte)
  347. if len(bits) == 8 {
  348. return int64(binary.LittleEndian.Uint64(bits))
  349. } else if len(bits) <= 4 {
  350. num, err := strconv.Atoi(string(bits))
  351. if err != nil {
  352. return d
  353. } else {
  354. return int64(num)
  355. }
  356. }
  357. case uint:
  358. return int64(i.(uint))
  359. case uint8:
  360. return int64(i.(uint8))
  361. case uint16:
  362. return int64(i.(uint16))
  363. case uint32:
  364. return int64(i.(uint32))
  365. case uint64:
  366. return int64(i.(uint64))
  367. case int:
  368. return int64(i.(int))
  369. case int8:
  370. return int64(i.(int8))
  371. case int16:
  372. return int64(i.(int16))
  373. case int32:
  374. return int64(i.(int32))
  375. case int64:
  376. return i.(int64)
  377. case float32:
  378. return int64(i.(float32))
  379. case float64:
  380. return int64(i.(float64))
  381. }
  382. return d
  383. }
  384. // 从接口类型安全获取到字符串类型
  385. func GetString(str interface{}, d string) string {
  386. if str == nil {
  387. return d
  388. }
  389. switch str.(type) {
  390. case string:
  391. return str.(string)
  392. case []byte:
  393. return string(str.([]byte))
  394. }
  395. return fmt.Sprintf("%s", str)
  396. }
  397. // 从map中得到指定的key
  398. func GetInt64FromMap(dm map[string]interface{}, key string, dft int64) int64 {
  399. data, ok := dm[key]
  400. if !ok {
  401. return dft
  402. }
  403. return GetInt64(data, dft)
  404. }
  405. // 从map中得到指定的key
  406. func GetInt64FromStringMap(dm map[string]string, key string, dft int64) int64 {
  407. data, ok := dm[key]
  408. if !ok {
  409. return dft
  410. }
  411. return GetInt64(data, dft)
  412. }
  413. // 从map中得到指定的key
  414. func GetStringFromMap(dm map[string]interface{}, key string, dft string) string {
  415. data, ok := dm[key]
  416. if !ok {
  417. return dft
  418. }
  419. return GetString(data, dft)
  420. }
  421. // 从map中得到指定的key
  422. func GetStringFromStringMap(dm map[string]string, key string, dft string) string {
  423. data, ok := dm[key]
  424. if !ok {
  425. return dft
  426. }
  427. return data
  428. }
  429. // 首字母大写
  430. func Ucfirst(str string) string {
  431. for i, v := range str {
  432. return string(unicode.ToUpper(v)) + str[i+1:]
  433. }
  434. return ""
  435. }