util.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package util
  4. import (
  5. "errors"
  6. "math"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. )
  12. // SplitPath 将路径按分隔符分隔成字符串数组。比如:
  13. // /a/b/c ==> []string{"a", "b", "c"}
  14. func SplitPath(path string) []string {
  15. vol := filepath.VolumeName(path)
  16. ret := make([]string, 0, 10)
  17. index := 0
  18. if len(vol) > 0 {
  19. ret = append(ret, vol)
  20. path = path[len(vol)+1:]
  21. }
  22. for i := 0; i < len(path); i++ {
  23. if os.IsPathSeparator(path[i]) {
  24. if i > index {
  25. ret = append(ret, path[index:i])
  26. }
  27. index = i + 1 // 过滤掉此符号
  28. }
  29. } // end for
  30. if len(path) > index {
  31. ret = append(ret, path[index:])
  32. }
  33. return ret
  34. }
  35. // Round 返回浮点数四舍五入后的整数
  36. func Round(v float64) int64 {
  37. return int64(math.Round(v))
  38. }
  39. // MaxInt64 返回int64最大值
  40. func MaxInt64(x int, y int) int {
  41. if x >= y {
  42. return x
  43. }
  44. return y
  45. }
  46. // MinInt64 返回int64最小值
  47. func MinInt64(x int, y int) int {
  48. if x <= y {
  49. return x
  50. }
  51. return y
  52. }
  53. // MaxInt 返回int最大值
  54. func MaxInt(x int, y int) int {
  55. if x >= y {
  56. return x
  57. }
  58. return y
  59. }
  60. // MinInt 返回int最小值
  61. func MinInt(x int, y int) int {
  62. if x <= y {
  63. return x
  64. }
  65. return y
  66. }
  67. // IdCertGender 身份证的性别
  68. // 返回:1 => 男性,0 => 女性
  69. func IdCertGender(idcert string) (int, error) {
  70. if !IsIdCert(idcert) {
  71. return 0, errors.New("invalid idcert")
  72. }
  73. v, err := strconv.Atoi(idcert[17:17])
  74. if err != nil {
  75. return 0, err
  76. }
  77. return v / 2, nil
  78. }
  79. // 生成顺序码
  80. func GenerateCode(code, prefix string, width int) string {
  81. // 生成编码
  82. if code == "" {
  83. code = "0"
  84. }
  85. if prefix != "" {
  86. code = strings.Replace(code, prefix, "", -1)
  87. }
  88. codeInt, _ := strconv.Atoi(code)
  89. codeInt = codeInt + 1
  90. code = strconv.Itoa(codeInt)
  91. codeLen := len(code)
  92. if codeLen < width {
  93. for i := 0; i < width-codeLen; i++ {
  94. code = "0" + code
  95. }
  96. }
  97. if prefix != "" {
  98. code = prefix + code
  99. }
  100. return code
  101. }