tools.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package utils
  2. import (
  3. "github.com/gogf/gf/encoding/gcharset"
  4. "github.com/gogf/gf/encoding/gjson"
  5. "github.com/gogf/gf/frame/g"
  6. "github.com/gogf/gf/net/ghttp"
  7. "github.com/gogf/gf/os/gtime"
  8. "net"
  9. "time"
  10. )
  11. //服务端ip
  12. func GetLocalIP() (ip string, err error) {
  13. addrs, err := net.InterfaceAddrs()
  14. if err != nil {
  15. return
  16. }
  17. for _, addr := range addrs {
  18. ipAddr, ok := addr.(*net.IPNet)
  19. if !ok {
  20. continue
  21. }
  22. if ipAddr.IP.IsLoopback() {
  23. continue
  24. }
  25. if !ipAddr.IP.IsGlobalUnicast() {
  26. continue
  27. }
  28. return ipAddr.IP.String(), nil
  29. }
  30. return
  31. }
  32. //获取相差时间
  33. func GetHourDiffer(startTime, endTime string) int64 {
  34. var hour int64
  35. t1, err := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
  36. t2, err := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
  37. if err == nil && t1.Before(t2) {
  38. diff := t2.Unix() - t1.Unix() //
  39. hour = diff / 3600
  40. return hour
  41. } else {
  42. return hour
  43. }
  44. }
  45. //日期字符串转时间戳(秒)
  46. func StrToTimestamp(dateStr string) int64 {
  47. tm, err := gtime.StrToTime(dateStr)
  48. if err != nil {
  49. g.Log().Error(err)
  50. return 0
  51. }
  52. return tm.Timestamp()
  53. }
  54. //获取ip所属城市
  55. func GetCityByIp(ip string) string {
  56. if ip == "" {
  57. return ""
  58. }
  59. if ip == "[::1]" || ip == "127.0.0.1" {
  60. return "内网IP"
  61. }
  62. url := "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip
  63. bytes := ghttp.GetBytes(url)
  64. src := string(bytes)
  65. srcCharset := "GBK"
  66. tmp, _ := gcharset.ToUTF8(srcCharset, src)
  67. json, err := gjson.DecodeToJson(tmp)
  68. if err != nil {
  69. return ""
  70. }
  71. if json.GetInt("code") == 0 {
  72. city := json.GetString("city")
  73. return city
  74. } else {
  75. return ""
  76. }
  77. }