util.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. package util
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "crypto/rand"
  6. "database/sql"
  7. "encoding/hex"
  8. "fmt"
  9. "image"
  10. "io/ioutil"
  11. "math/big"
  12. "net/http"
  13. "regexp"
  14. "strings"
  15. "time"
  16. "surveyService/model/types"
  17. "github.com/gin-gonic/gin"
  18. jsoniter "github.com/json-iterator/go"
  19. "github.com/speps/go-hashids/v2"
  20. )
  21. // php序列化的对象转map之后,key值会有特定的字节前缀导致无法解析,需要去掉
  22. func PhpMap2Go(in map[string]interface{}) map[string]interface{} {
  23. result := make(map[string]interface{})
  24. for i, v := range in {
  25. tmpi := []byte(i)
  26. if tmpi[0] == 0 && tmpi[1] == 42 && tmpi[2] == 0 {
  27. result[string(tmpi[3:])] = v
  28. } else {
  29. result[i] = v
  30. }
  31. }
  32. return result
  33. }
  34. func GetRequestParam(c *gin.Context, key string) string {
  35. if c.Request.Method == http.MethodGet {
  36. return c.Query(key)
  37. } else {
  38. // 如果是Json格式
  39. if c.Request.Header.Get("Content-Type") == "application/json" {
  40. JsonData := GetRequestJsonData(c)
  41. // 判断类型
  42. if _, ok := JsonData[key].(string); !ok {
  43. return ""
  44. }
  45. return JsonData[key].(string)
  46. }
  47. return c.PostForm(key)
  48. }
  49. }
  50. func GetRequestJsonData(c *gin.Context) map[string]any {
  51. data, _ := c.GetRawData()
  52. var body map[string]any
  53. _ = json.Unmarshal(data, &body)
  54. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data))
  55. return body
  56. }
  57. func GetPostFormParams(c *gin.Context) (map[string]any, error) {
  58. var postMap = make(map[string]any, len(c.Request.PostForm))
  59. for k, v := range c.Request.PostForm {
  60. if len(v) > 1 {
  61. postMap[k] = v
  62. } else if len(v) == 1 {
  63. postMap[k] = v[0]
  64. }
  65. }
  66. return postMap, nil
  67. }
  68. // 将ID编译为HashId
  69. func GetHashId(id int64, salt string) string {
  70. hd := hashids.NewData()
  71. hd.Salt = salt
  72. hd.MinLength = 8
  73. h, _ := hashids.NewWithData(hd)
  74. hashId, _ := h.Encode([]int{int(id)})
  75. return hashId
  76. }
  77. // 根据HashId获取真实ID
  78. func GetIdByHashId(hashId string, salt string) (int64, error) {
  79. hd := hashids.NewData()
  80. hd.Salt = salt
  81. hd.MinLength = 8
  82. h, _ := hashids.NewWithData(hd)
  83. d, err := h.DecodeWithError(hashId)
  84. if err != nil {
  85. return 0, err
  86. }
  87. return int64(d[0]), nil
  88. }
  89. func GetFromGinContext[T any](ctx *gin.Context, key string) (T, bool) {
  90. var some T
  91. value, exist := ctx.Get(key)
  92. if !exist {
  93. return some, false
  94. }
  95. some, ok := value.(T)
  96. if !ok {
  97. return some, false
  98. }
  99. return some, true
  100. }
  101. // MD5加密
  102. func Md5(src string) string {
  103. m := md5.New()
  104. m.Write([]byte(src))
  105. res := hex.EncodeToString(m.Sum(nil))
  106. return res
  107. }
  108. // 获取随机数
  109. func GetRandomNumber() string {
  110. result, _ := rand.Int(rand.Reader, big.NewInt(9999))
  111. return fmt.Sprintf("%04d", result)
  112. }
  113. // 转为sql.NullTime
  114. func ToNullTime(t time.Time) types.NullTime {
  115. return types.NullTime{NullTime: sql.NullTime{Time: t, Valid: !t.IsZero()}}
  116. }
  117. // 数据脱敏
  118. func HideStar(str string) (result string) {
  119. if str == "" {
  120. return ""
  121. }
  122. if strings.Contains(str, "@") { // 邮箱
  123. res := strings.Split(str, "@")
  124. if len(res[0]) < 3 {
  125. resString := "***"
  126. result = resString + "@" + res[1]
  127. } else {
  128. res2 := Substr2(str, 0, 3)
  129. resString := res2 + "***"
  130. result = resString + "@" + res[1]
  131. }
  132. return result
  133. } else {
  134. reg := `^1[0-9]\d{9}$`
  135. rgx := regexp.MustCompile(reg)
  136. mobileMatch := rgx.MatchString(str)
  137. if mobileMatch { // 手机号
  138. result = Substr2(str, 0, 3) + "****" + Substr2(str, 7, 11)
  139. } else {
  140. nameRune := []rune(str)
  141. lens := len(nameRune)
  142. if lens <= 1 {
  143. result = "***"
  144. } else if lens == 2 {
  145. result = string(nameRune[:1]) + "*"
  146. } else if lens == 3 {
  147. result = string(nameRune[:1]) + "*" + string(nameRune[2:3])
  148. } else if lens == 4 {
  149. result = string(nameRune[:1]) + "**" + string(nameRune[lens-1:lens])
  150. } else if lens > 4 {
  151. result = string(nameRune[:2]) + "***" + string(nameRune[lens-2:lens])
  152. }
  153. }
  154. return
  155. }
  156. }
  157. func Substr2(str string, start int, end int) string {
  158. rs := []rune(str)
  159. return string(rs[start:end])
  160. }
  161. // 读取远程文件
  162. func ReadImageData(url string) image.Image {
  163. resp, err := http.Get(url)
  164. if err != nil {
  165. return nil
  166. }
  167. defer resp.Body.Close()
  168. img, _, err := image.Decode(resp.Body)
  169. if err != nil {
  170. return nil
  171. }
  172. return img
  173. }
  174. // 获取随机字符串
  175. func RandString(n int) string {
  176. var longLetters = []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_")
  177. if n <= 0 {
  178. return ""
  179. }
  180. b := make([]byte, n)
  181. arc := uint8(0)
  182. if _, err := rand.Read(b[:]); err != nil {
  183. return ""
  184. }
  185. for i, x := range b {
  186. arc = x & 62
  187. b[i] = longLetters[arc]
  188. }
  189. return string(b)
  190. }
  191. var json = jsoniter.ConfigCompatibleWithStandardLibrary
  192. func JsonEncode(v interface{}) string {
  193. str, _ := json.MarshalToString(v)
  194. return str
  195. }
  196. func Println(v interface{}) string {
  197. var str string
  198. // 判断是否是string类型
  199. str = JsonEncode(str)
  200. return str
  201. }
  202. func InArrayString(val string, arr []string) bool {
  203. for _, v := range arr {
  204. if v == val {
  205. return true
  206. }
  207. }
  208. return false
  209. }
  210. // 手机号
  211. func RegexMobile(mobile string) bool {
  212. if matched, _ := regexp.MatchString(`^1[3456789]\d{9}$`, mobile); matched {
  213. return true
  214. }
  215. return false
  216. }