client.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package utils
  2. import (
  3. "github.com/gogf/gf/v2/encoding/gcharset"
  4. "github.com/gogf/gf/v2/encoding/gjson"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/os/gctx"
  7. "github.com/mssola/user_agent"
  8. )
  9. // GetClientBrowserInfo 获取浏览器信息
  10. func GetClientBrowserInfo(clientIP, userAgent string) (string, string, string) {
  11. ua := user_agent.New(userAgent)
  12. browser, _ := ua.Browser()
  13. return ua.OS(), browser, GetClientCityByIp(clientIP)
  14. }
  15. // GetClientCityByIp 获取ip所属城市
  16. func GetClientCityByIp(ip string) string {
  17. if ip == "" {
  18. return ""
  19. }
  20. if ip == "[::1]" || ip == "127.0.0.1" {
  21. return "内网IP"
  22. }
  23. url := "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip
  24. bytes := g.Client().GetBytes(gctx.New(), url)
  25. src := string(bytes)
  26. srcCharset := "GBK"
  27. tmp, _ := gcharset.ToUTF8(srcCharset, src)
  28. resData, err := gjson.DecodeToJson(tmp)
  29. if err != nil {
  30. return ""
  31. }
  32. if resData.Get("code").Int() == 0 {
  33. pro := resData.Get("pro").String()
  34. city := resData.Get("city").String()
  35. return pro + city
  36. } else {
  37. return ""
  38. }
  39. }