string.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. package util
  2. import (
  3. "crypto/md5"
  4. "fmt"
  5. "net/url"
  6. "strconv"
  7. "strings"
  8. )
  9. func SplitIgnoreSpace(str string, sep string) []string {
  10. split := strings.Split(str, sep)
  11. result := make([]string, 0, len(split))
  12. for _, elem := range split {
  13. value := strings.TrimSpace(elem)
  14. if value == "" {
  15. continue
  16. }
  17. result = append(result, value)
  18. }
  19. return result
  20. }
  21. func JoinIgnoreSpace(str []string, sep string) string {
  22. if str == nil || len(str) == 0 {
  23. return ""
  24. }
  25. builder := strings.Builder{}
  26. for index, elem := range str {
  27. if elem == "" {
  28. continue
  29. }
  30. builder.WriteString(elem)
  31. if index != len(str)-1 { // not latest index
  32. builder.WriteString(sep)
  33. }
  34. }
  35. return builder.String()
  36. }
  37. func ToString(value interface{}) string {
  38. switch v := value.(type) {
  39. case string:
  40. return v
  41. case uint8, uint16, uint32, uint64:
  42. convertUint64 := func(value interface{}) uint64 {
  43. switch v := value.(type) {
  44. case uint8:
  45. return uint64(v)
  46. case uint16:
  47. return uint64(v)
  48. case uint32:
  49. return uint64(v)
  50. case uint64:
  51. return v
  52. default:
  53. return 0
  54. }
  55. }
  56. return strconv.FormatUint(convertUint64(value), 10)
  57. case int, int8, int16, int32, int64:
  58. convertInt64 := func(value interface{}) int64 {
  59. switch v := value.(type) {
  60. case int8:
  61. return int64(v)
  62. case int16:
  63. return int64(v)
  64. case int32:
  65. return int64(v)
  66. case int64:
  67. return v
  68. case int:
  69. return int64(v)
  70. default:
  71. return 0
  72. }
  73. }
  74. return strconv.FormatInt(convertInt64(value), 10)
  75. case bool:
  76. if v {
  77. return "true"
  78. }
  79. return "false"
  80. // float 效率和直接fmt差距相差不大,为了保证不出问题,还是使用%v
  81. default:
  82. str, isOk := value.(fmt.Stringer)
  83. if isOk {
  84. return str.String()
  85. }
  86. return fmt.Sprintf("%+v", value)
  87. }
  88. }
  89. // 解码失败则返回原数据
  90. func UrlDecode(str string) string {
  91. oldStr := str
  92. str, err := url.QueryUnescape(str)
  93. if err != nil {
  94. return oldStr
  95. }
  96. return str
  97. }
  98. // 编码url
  99. func UrlEncode(str string) string {
  100. return url.QueryEscape(str)
  101. }
  102. func String2Md5(str string) string {
  103. data := []byte(str)
  104. has := md5.Sum(data)
  105. md5str := fmt.Sprintf("%x", has)
  106. return md5str
  107. }