互动
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.3 KiB

5 years ago
  1. package utils
  2. import (
  3. "crypto/sha1"
  4. "encoding/base64"
  5. "fmt"
  6. "github.com/skip2/go-qrcode"
  7. "hudongzhuanjia/utils/define"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "strconv"
  12. "strings"
  13. )
  14. func Int(str string) int {
  15. i, _ := strconv.Atoi(str)
  16. return i
  17. }
  18. func Int64(str string) int64 {
  19. i, _ := strconv.ParseInt(str, 10, 64)
  20. return i
  21. }
  22. func Float64(str string) float64 {
  23. f, _ := strconv.ParseFloat(strings.TrimSpace(str), 64)
  24. return f
  25. }
  26. //除法,校验被除数为0时返回接口为0
  27. // return one/two
  28. func Except(one, two float64) float64 {
  29. if two == 0 {
  30. return 0
  31. }
  32. return one / two
  33. }
  34. //自定义小数的位数
  35. func Float64CusDecimal(v float64, decimal int) float64 {
  36. return Float64(fmt.Sprintf("%."+fmt.Sprintf("%d", decimal)+"f", v))
  37. }
  38. func Qrcode2Base64(url string) (string, error) {
  39. qr, err := qrcode.Encode(url, qrcode.Medium, 256)
  40. return fmt.Sprintf("data:image/png;base64,%s", base64.StdEncoding.EncodeToString(qr)), err
  41. }
  42. func GenH5Url(webName string, param map[string]interface{}) string {
  43. path := fmt.Sprintf("%s/%s?", define.H5Host, webName)
  44. for key, value := range param {
  45. if key[len(key)-1] == '=' {
  46. key = key[:len(key)-1]
  47. }
  48. path += fmt.Sprintf("%s=%v&", key, value)
  49. }
  50. lastChar := path[len(path)-1]
  51. if lastChar == '&' || lastChar == '?' {
  52. path = path[:len(path)-1]
  53. }
  54. return path
  55. }
  56. func GenH5Qrcode(WebName string, param map[string]interface{}) (string, error) {
  57. path := GenH5Url(WebName, param)
  58. return Qrcode2Base64(path)
  59. }
  60. func Gif2Base64(url string) (string, error) {
  61. if strings.HasSuffix(url, ".gif") {
  62. resp, err := http.Get(url)
  63. if err != nil {
  64. return "", err
  65. }
  66. bys, err := ioutil.ReadAll(resp.Body)
  67. if err != nil {
  68. return "", err
  69. }
  70. return fmt.Sprintf("data:image/gif;base64,%s", base64.StdEncoding.EncodeToString(bys)), err
  71. }
  72. return url, nil
  73. }
  74. func Sha1(b string) string {
  75. h := sha1.New()
  76. h.Write([]byte(b))
  77. return fmt.Sprintf("%x", h.Sum(nil))
  78. }
  79. func PathExists(path string) (bool, error) {
  80. _, err := os.Stat(path)
  81. if err == nil {
  82. return true, nil
  83. }
  84. if os.IsNotExist(err) {
  85. return false, nil
  86. }
  87. return false, err
  88. }
  89. func CountDownFormat(duration int64) string {
  90. m := duration / 60 // 分钟
  91. s := duration - m*60 // 剩余秒
  92. h := m / 60 // 小时
  93. m = m - h*60 // 剩余分钟
  94. return fmt.Sprintf("%02d:%02d:%02d", h, m, s)
  95. }