string.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /**********************************************
  2. ** @Des: This file ...
  3. ** @Author: haodaquan
  4. ** @Date: 2017-09-08 00:24:25
  5. ** @Last Modified by: haodaquan
  6. ** @Last Modified time: 2017-09-17 10:12:06
  7. ***********************************************/
  8. package libs
  9. import (
  10. "crypto/md5"
  11. "fmt"
  12. "math/rand"
  13. "regexp"
  14. "time"
  15. "github.com/bitly/go-simplejson"
  16. "strconv"
  17. "encoding/json"
  18. )
  19. var emailPattern = regexp.MustCompile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?")
  20. func Md5(buf []byte) string {
  21. hash := md5.New()
  22. hash.Write(buf)
  23. return fmt.Sprintf("%x", hash.Sum(nil))
  24. }
  25. func SizeFormat(size float64) string {
  26. units := []string{"Byte", "KB", "MB", "GB", "TB"}
  27. n := 0
  28. for size > 1024 {
  29. size /= 1024
  30. n += 1
  31. }
  32. return fmt.Sprintf("%.2f %s", size, units[n])
  33. }
  34. func IsEmail(b []byte) bool {
  35. return emailPattern.Match(b)
  36. }
  37. func Password(len int, pwdO string) (pwd string, salt string) {
  38. salt = GetRandomString(4)
  39. defaultPwd := "george518"
  40. if pwdO != "" {
  41. defaultPwd = pwdO
  42. }
  43. pwd = Md5([]byte(defaultPwd + salt))
  44. return pwd, salt
  45. }
  46. // 生成32位MD5
  47. // func MD5(text string) string{
  48. // ctx := md5.New()
  49. // ctx.Write([]byte(text))
  50. // return hex.EncodeToString(ctx.Sum(nil))
  51. // }
  52. //生成随机字符串
  53. func GetRandomString(lens int) string {
  54. str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  55. bytes := []byte(str)
  56. result := []byte{}
  57. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  58. for i := 0; i < lens; i++ {
  59. result = append(result, bytes[r.Intn(len(bytes))])
  60. }
  61. return string(result)
  62. }
  63. // json转换成map
  64. func JsonToMap(value string)(map[string]interface{}){
  65. byteValue := []byte(value)
  66. js, _ := simplejson.NewJson(byteValue)
  67. nodes, _ := js.Map()
  68. return nodes
  69. }
  70. // map转换为json
  71. func MapToJson(value interface{}) string {
  72. jsonStr,_ := json.Marshal(value)
  73. return string(jsonStr)
  74. }
  75. // 转化成字符串
  76. func ConvertString(value interface{})string{
  77. switch value.(type) {
  78. case string:
  79. return value.(string)
  80. case int:
  81. return strconv.Itoa(value.(int))
  82. default:
  83. return ""
  84. }
  85. }