common.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. package util
  2. import (
  3. "crypto/md5"
  4. cryptoRand "crypto/rand"
  5. "encoding/hex"
  6. "encoding/json"
  7. "encoding/xml"
  8. "fmt"
  9. "io"
  10. "log"
  11. "math/big"
  12. mathRand "math/rand"
  13. "reflect"
  14. "regexp"
  15. "runtime"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. const (
  22. tmp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345678900"
  23. )
  24. func Uuid(length int) string {
  25. ret := []string{}
  26. r := mathRand.New(mathRand.NewSource(time.Now().UnixNano()))
  27. for i := 0; i < length; i++ {
  28. index := r.Intn(62)
  29. ret = append(ret, tmp[index:index+1])
  30. }
  31. return strings.Join(ret, "")
  32. }
  33. //计算字符串和值
  34. func Sumstring(code string) (sum int) {
  35. tmp := []rune(code)
  36. for _, v := range tmp {
  37. sum = sum + int(v)
  38. }
  39. return
  40. }
  41. //获取复杂的随机数
  42. func GetLetterRandom(length int, flag ...bool) string {
  43. var idChars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
  44. var mod byte = 52
  45. if len(flag) > 0 && flag[0] {
  46. idChars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
  47. mod = 26
  48. }
  49. b := make([]byte, length)
  50. maxrb := byte(256 - (256 % int(mod)))
  51. i := 0
  52. EXIT:
  53. for {
  54. r := make([]byte, length+(length/4))
  55. if _, err := io.ReadFull(cryptoRand.Reader, r); err != nil {
  56. panic("captcha: error reading random source: " + err.Error())
  57. }
  58. for _, c := range r {
  59. if c > maxrb {
  60. continue
  61. }
  62. b[i] = c % mod
  63. i++
  64. if i == length {
  65. break EXIT
  66. }
  67. }
  68. }
  69. for i, c := range b {
  70. b[i] = idChars[c]
  71. }
  72. return string(b)
  73. }
  74. /*隐藏部分账号
  75. *返回手机号:150...70765 邮箱:...shenjun@vip.qq.com
  76. */
  77. func EncryCode(value string) string {
  78. if len(value) == 0 {
  79. return value
  80. } else if strings.Contains(value, "@") {
  81. start := strings.Index(value, "@") / 2
  82. if start == 0 {
  83. start++
  84. }
  85. value = "...." + string(value[start:])
  86. } else {
  87. value = string(value[0:3]) + "..." + string(value[len(value)-4:])
  88. }
  89. return value
  90. }
  91. //生成32位md5字串
  92. func GetMd5String(s string) string {
  93. h := md5.New()
  94. h.Write([]byte(s))
  95. return hex.EncodeToString(h.Sum(nil))
  96. }
  97. //obj(string,M)转M,查询用到
  98. func ObjToMap(obj interface{}) *map[string]interface{} {
  99. data := make(map[string]interface{})
  100. if s, ok := obj.(string); ok {
  101. json.Unmarshal([]byte(strings.Replace(s, "'", "\"", -1)), &data)
  102. } else if s1, ok1 := obj.(map[string]interface{}); ok1 {
  103. data = s1
  104. } else if s1, ok1 := obj.(*map[string]interface{}); ok1 {
  105. return s1
  106. } else {
  107. data = nil
  108. }
  109. return &data
  110. }
  111. /*UTC类型时间转字符串
  112. *flag==true,日期格式yyyy-mm-dd hh:mm:ss
  113. *flag==false,日期格式yyyy-mm-dd
  114. */
  115. func LongToDate(date interface{}, flag bool) string {
  116. var int64Date int64
  117. if l1, ok1 := date.(float64); ok1 {
  118. int64Date = int64(l1)
  119. } else if l2, ok2 := date.(int64); ok2 {
  120. int64Date = l2
  121. } else if l3, ok3 := date.(int); ok3 {
  122. int64Date = int64(l3)
  123. }
  124. t := time.Unix(int64Date, 0)
  125. if flag {
  126. return t.Format("2006-01-02 15:04:05")
  127. } else {
  128. return t.Format("2006-01-02")
  129. }
  130. }
  131. func IntAll(num interface{}) int {
  132. return IntAllDef(num, 0)
  133. }
  134. func Int64All(num interface{}) int64 {
  135. if i, ok := num.(int64); ok {
  136. return int64(i)
  137. } else if i0, ok0 := num.(int32); ok0 {
  138. return int64(i0)
  139. } else if i1, ok1 := num.(float64); ok1 {
  140. return int64(i1)
  141. } else if i2, ok2 := num.(int); ok2 {
  142. return int64(i2)
  143. } else if i3, ok3 := num.(float32); ok3 {
  144. return int64(i3)
  145. } else if i4, ok4 := num.(string); ok4 {
  146. i64, _ := strconv.ParseInt(i4, 10, 64)
  147. //in, _ := strconv.Atoi(i4)
  148. return i64
  149. } else if i5, ok5 := num.(int16); ok5 {
  150. return int64(i5)
  151. } else if i6, ok6 := num.(int8); ok6 {
  152. return int64(i6)
  153. } else if i7, ok7 := num.(*big.Int); ok7 {
  154. in, _ := strconv.ParseInt(fmt.Sprint(i7), 10, 64)
  155. return int64(in)
  156. } else if i8, ok8 := num.(*big.Float); ok8 {
  157. in, _ := strconv.ParseInt(fmt.Sprint(i8), 10, 64)
  158. return int64(in)
  159. } else {
  160. return 0
  161. }
  162. }
  163. func Float64All(num interface{}) float64 {
  164. if i, ok := num.(float64); ok {
  165. return float64(i)
  166. } else if i0, ok0 := num.(int32); ok0 {
  167. return float64(i0)
  168. } else if i1, ok1 := num.(int64); ok1 {
  169. return float64(i1)
  170. } else if i2, ok2 := num.(int); ok2 {
  171. return float64(i2)
  172. } else if i3, ok3 := num.(float32); ok3 {
  173. return float64(i3)
  174. } else if i4, ok4 := num.(string); ok4 {
  175. in, _ := strconv.ParseFloat(i4, 64)
  176. return in
  177. } else if i5, ok5 := num.(int16); ok5 {
  178. return float64(i5)
  179. } else if i6, ok6 := num.(int8); ok6 {
  180. return float64(i6)
  181. } else if i6, ok6 := num.(uint); ok6 {
  182. return float64(i6)
  183. } else if i6, ok6 := num.(uint8); ok6 {
  184. return float64(i6)
  185. } else if i6, ok6 := num.(uint16); ok6 {
  186. return float64(i6)
  187. } else if i6, ok6 := num.(uint32); ok6 {
  188. return float64(i6)
  189. } else if i6, ok6 := num.(uint64); ok6 {
  190. return float64(i6)
  191. } else if i7, ok7 := num.(*big.Float); ok7 {
  192. in, _ := strconv.ParseFloat(fmt.Sprint(i7), 64)
  193. return float64(in)
  194. } else if i8, ok8 := num.(*big.Int); ok8 {
  195. in, _ := strconv.ParseFloat(fmt.Sprint(i8), 64)
  196. return float64(in)
  197. } else {
  198. return 0
  199. }
  200. }
  201. func IntAllDef(num interface{}, defaultNum int) int {
  202. if i, ok := num.(int); ok {
  203. return int(i)
  204. } else if i0, ok0 := num.(int32); ok0 {
  205. return int(i0)
  206. } else if i1, ok1 := num.(float64); ok1 {
  207. return int(i1)
  208. } else if i2, ok2 := num.(int64); ok2 {
  209. return int(i2)
  210. } else if i3, ok3 := num.(float32); ok3 {
  211. return int(i3)
  212. } else if i4, ok4 := num.(string); ok4 {
  213. in, _ := strconv.Atoi(i4)
  214. return int(in)
  215. } else if i5, ok5 := num.(int16); ok5 {
  216. return int(i5)
  217. } else if i6, ok6 := num.(int8); ok6 {
  218. return int(i6)
  219. } else if i7, ok7 := num.(*big.Int); ok7 {
  220. in, _ := strconv.Atoi(fmt.Sprint(i7))
  221. return int(in)
  222. } else if i8, ok8 := num.(*big.Float); ok8 {
  223. in, _ := strconv.Atoi(fmt.Sprint(i8))
  224. return int(in)
  225. } else {
  226. return defaultNum
  227. }
  228. }
  229. func ObjToString(old interface{}) string {
  230. if nil == old {
  231. return ""
  232. } else {
  233. r, _ := old.(string)
  234. return r
  235. }
  236. }
  237. func ObjToStringDef(old interface{}, defaultstr string) string {
  238. if nil == old {
  239. return defaultstr
  240. } else {
  241. r, _ := old.(string)
  242. if r == "" {
  243. return defaultstr
  244. }
  245. return r
  246. }
  247. }
  248. //对象数组转成string数组
  249. func ObjArrToStringArr(old []interface{}) []string {
  250. if old != nil {
  251. new := make([]string, len(old))
  252. for i, v := range old {
  253. new[i] = v.(string)
  254. }
  255. return new
  256. } else {
  257. return nil
  258. }
  259. }
  260. //对象数组转成map数组
  261. func ObjArrToMapArr(old []interface{}) []map[string]interface{} {
  262. if old != nil {
  263. new := make([]map[string]interface{}, len(old))
  264. for i, v := range old {
  265. new[i] = v.(map[string]interface{})
  266. }
  267. return new
  268. } else {
  269. return nil
  270. }
  271. }
  272. //map数组转成对象数组
  273. func MapArrToObjArr(old []map[string]interface{}) []interface{} {
  274. if old != nil {
  275. new := make([]interface{}, len(old))
  276. for i, v := range old {
  277. new[i] = v
  278. }
  279. return new
  280. } else {
  281. return nil
  282. }
  283. }
  284. func SubstrByByte(str string, length int) string {
  285. bs := []byte(str)[:length]
  286. bl := 0
  287. for i := len(bs) - 1; i >= 0; i-- {
  288. switch {
  289. case bs[i] >= 0 && bs[i] <= 127:
  290. return string(bs[:i+1])
  291. case bs[i] >= 128 && bs[i] <= 191:
  292. bl++
  293. case bs[i] >= 192 && bs[i] <= 253:
  294. cl := 0
  295. switch {
  296. case bs[i]&252 == 252:
  297. cl = 6
  298. case bs[i]&248 == 248:
  299. cl = 5
  300. case bs[i]&240 == 240:
  301. cl = 4
  302. case bs[i]&224 == 224:
  303. cl = 3
  304. default:
  305. cl = 2
  306. }
  307. if bl+1 == cl {
  308. return string(bs[:i+cl])
  309. }
  310. return string(bs[:i])
  311. }
  312. }
  313. return ""
  314. }
  315. func SubString(str string, begin, length int) (substr string) {
  316. // 将字符串的转换成[]rune
  317. rs := []rune(str)
  318. lth := len(rs)
  319. // 简单的越界判断
  320. if begin < 0 {
  321. begin = 0
  322. }
  323. if begin >= lth {
  324. begin = lth
  325. }
  326. end := begin + length
  327. if end > lth {
  328. end = lth
  329. }
  330. // 返回子串
  331. return string(rs[begin:end])
  332. }
  333. //捕获异常
  334. func Try(fun func(), handler func(interface{})) {
  335. defer func() {
  336. if err := recover(); err != nil {
  337. for skip := 1; ; skip++ {
  338. _, file, line, ok := runtime.Caller(skip)
  339. if !ok {
  340. break
  341. }
  342. log.Printf("%v,%v\n", file, line)
  343. }
  344. handler(err)
  345. }
  346. }()
  347. fun()
  348. }
  349. //3目运算
  350. func If(b bool, to, fo interface{}) interface{} {
  351. if b {
  352. return to
  353. } else {
  354. return fo
  355. }
  356. }
  357. //HashCode值
  358. func HashCode(uid string) int {
  359. var h uint32 = 0
  360. rs := []rune(uid)
  361. for i := 0; i < len(rs); i++ {
  362. h = 31*h + uint32(rs[i])
  363. }
  364. return int(h)
  365. }
  366. //获取离n天的秒差
  367. func GetDayStartSecond(n int) int64 {
  368. now := time.Now()
  369. tom := time.Date(now.Year(), now.Month(), now.Day()+n, 0, 0, 0, 0, time.Local)
  370. return tom.Unix()
  371. }
  372. func InterfaceArrTointArr(arr []interface{}) []int {
  373. tmp := make([]int, 0)
  374. for _, v := range arr {
  375. tmp = append(tmp, int(v.(float64)))
  376. }
  377. return tmp
  378. }
  379. func InterfaceArrToint64Arr(arr []interface{}) []int64 {
  380. tmp := make([]int64, 0)
  381. for _, v := range arr {
  382. tmp = append(tmp, int64(v.(float64)))
  383. }
  384. return tmp
  385. }
  386. func GetSubDay(t1 int64) int {
  387. tt1 := time.Unix(t1, 0)
  388. tt2 := time.Now()
  389. nt1 := time.Date(tt1.Year(), tt1.Month(), tt1.Day(), 0, 0, 0, 0, time.Local)
  390. nt2 := time.Date(tt2.Year(), tt2.Month(), tt2.Day(), 0, 0, 0, 0, time.Local)
  391. return int((nt1.Unix() - nt2.Unix()) / 86400)
  392. }
  393. func StartWith(value, str string) bool {
  394. ok, _ := regexp.MatchString("^"+str, value)
  395. return ok
  396. }
  397. func EndWith(value, str string) bool {
  398. ok, _ := regexp.MatchString(str+"$", value)
  399. return ok
  400. }
  401. //出错拦截
  402. func Catch() {
  403. if r := recover(); r != nil {
  404. log.Println(r)
  405. for skip := 0; ; skip++ {
  406. _, file, line, ok := runtime.Caller(skip)
  407. if !ok {
  408. break
  409. }
  410. log.Printf("%v,%v\n", file, line)
  411. }
  412. }
  413. }
  414. func ConvertFileSize(s int) string {
  415. size := float64(s)
  416. var kb float64 = 1024
  417. var mb float64 = kb * 1024
  418. var gb float64 = mb * 1024
  419. if size >= gb {
  420. return fmt.Sprintf("%.1f GB", float64(size/gb))
  421. } else if size >= mb {
  422. f := float64(size / mb)
  423. if f > 100 {
  424. return fmt.Sprintf("%.0f MB", f)
  425. }
  426. return fmt.Sprintf("%.1f MB", f)
  427. } else if size >= kb {
  428. f := float64(size / kb)
  429. if f > 100 {
  430. return fmt.Sprintf("%.0f KB", f)
  431. }
  432. return fmt.Sprintf("%.1f KB", f)
  433. }
  434. return fmt.Sprintf("%d B", s)
  435. }
  436. //MD5签名
  437. func WxSign(format string, param ...interface{}) string {
  438. data := fmt.Sprintf(format, param...)
  439. h := md5.New()
  440. h.Write([]byte(data))
  441. sign := strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
  442. return sign
  443. }
  444. func FloatFormat(tmp float64, n int) float64 {
  445. fs := fmt.Sprintf("%."+fmt.Sprint(n)+"f", tmp)
  446. f, _ := strconv.ParseFloat(fs, 64)
  447. return f
  448. }
  449. //生成微信支付的签名
  450. func CreateWxSign(afterStr string, obj interface{}, filter ...string) string {
  451. filter = append(filter, "sign", "xml")
  452. keys := []string{}
  453. m := make(map[string]string)
  454. t := reflect.TypeOf(obj)
  455. v := reflect.ValueOf(obj)
  456. k := t.Kind()
  457. if t.Kind() == reflect.Ptr {
  458. t = t.Elem()
  459. k = t.Kind()
  460. v = v.Elem()
  461. }
  462. if k == reflect.Map {
  463. for _, key := range v.MapKeys() {
  464. keys = append(keys, key.String())
  465. m[key.String()] = fmt.Sprint(v.MapIndex(key).Interface())
  466. }
  467. } else if k == reflect.Struct {
  468. for n := 0; n < t.NumField(); n++ {
  469. tagName := t.Field(n).Tag.Get("xml")
  470. if tagName == "" {
  471. tagName = t.Field(n).Tag.Get("json")
  472. }
  473. if tagName == "" {
  474. tagName = t.Field(n).Name
  475. }
  476. keys = append(keys, tagName)
  477. m[tagName] = fmt.Sprint(v.Field(n))
  478. }
  479. }
  480. sort.Strings(keys)
  481. vs := []string{}
  482. L:
  483. for _, v := range keys {
  484. for _, f := range filter {
  485. if f == v {
  486. continue L
  487. }
  488. }
  489. if strings.TrimSpace(m[v]) == "" {
  490. continue
  491. }
  492. vs = append(vs, fmt.Sprintf("%s=%s", v, m[v]))
  493. }
  494. return WxSign(strings.Join(vs, "&") + afterStr)
  495. }
  496. //简单的xml转map,只有一个层级,没有多层嵌套
  497. func XmlToMap(input string) map[string]string {
  498. var t xml.Token
  499. var err error
  500. inputReader := strings.NewReader(input)
  501. decoder := xml.NewDecoder(inputReader)
  502. isStart := false
  503. nodeName := ""
  504. m := make(map[string]string)
  505. for t, err = decoder.Token(); err == nil; t, err = decoder.Token() {
  506. switch token := t.(type) {
  507. // 处理元素开始(标签)
  508. case xml.StartElement:
  509. isStart = true
  510. nodeName = token.Name.Local
  511. // 处理元素结束(标签)
  512. case xml.EndElement:
  513. isStart = false
  514. // 处理字符数据(这里就是元素的文本)
  515. case xml.CharData:
  516. if isStart {
  517. m[nodeName] = string([]byte(token))
  518. }
  519. default:
  520. // ...
  521. }
  522. }
  523. return m
  524. }