utils.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * @desc:工具
  3. * @company:云南奇讯科技有限公司
  4. * @Author: yixiaohu
  5. * @Date: 2022/3/4 22:16
  6. */
  7. package libUtils
  8. import (
  9. "context"
  10. "fmt"
  11. "github.com/gogf/gf/v2/crypto/gmd5"
  12. "github.com/gogf/gf/v2/encoding/gcharset"
  13. "github.com/gogf/gf/v2/encoding/gjson"
  14. "github.com/gogf/gf/v2/encoding/gurl"
  15. "github.com/gogf/gf/v2/frame/g"
  16. "github.com/gogf/gf/v2/net/ghttp"
  17. "net"
  18. )
  19. // EncryptPassword 密码加密
  20. func EncryptPassword(password, salt string) string {
  21. return gmd5.MustEncryptString(gmd5.MustEncryptString(password) + gmd5.MustEncryptString(salt))
  22. }
  23. // GetDomain 获取当前请求接口域名
  24. func GetDomain(ctx context.Context) string {
  25. r := g.RequestFromCtx(ctx)
  26. pathInfo, err := gurl.ParseURL(r.GetUrl(), -1)
  27. if err != nil {
  28. g.Log().Error(ctx, err)
  29. return ""
  30. }
  31. return fmt.Sprintf("%s://%s:%s/", pathInfo["scheme"], pathInfo["host"], pathInfo["port"])
  32. }
  33. // GetClientIp 获取客户端IP
  34. func GetClientIp(ctx context.Context) string {
  35. return g.RequestFromCtx(ctx).GetClientIp()
  36. }
  37. // GetUserAgent 获取user-agent
  38. func GetUserAgent(ctx context.Context) string {
  39. return ghttp.RequestFromCtx(ctx).Header.Get("User-Agent")
  40. }
  41. // GetLocalIP 服务端ip
  42. func GetLocalIP() (ip string, err error) {
  43. var addrs []net.Addr
  44. addrs, err = net.InterfaceAddrs()
  45. if err != nil {
  46. return
  47. }
  48. for _, addr := range addrs {
  49. ipAddr, ok := addr.(*net.IPNet)
  50. if !ok {
  51. continue
  52. }
  53. if ipAddr.IP.IsLoopback() {
  54. continue
  55. }
  56. if !ipAddr.IP.IsGlobalUnicast() {
  57. continue
  58. }
  59. return ipAddr.IP.String(), nil
  60. }
  61. return
  62. }
  63. // GetCityByIp 获取ip所属城市
  64. func GetCityByIp(ip string) string {
  65. if ip == "" {
  66. return ""
  67. }
  68. if ip == "[::1]" || ip == "127.0.0.1" {
  69. return "内网IP"
  70. }
  71. url := "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip
  72. bytes := g.Client().GetBytes(context.TODO(), url)
  73. src := string(bytes)
  74. srcCharset := "GBK"
  75. tmp, _ := gcharset.ToUTF8(srcCharset, src)
  76. json, err := gjson.DecodeToJson(tmp)
  77. if err != nil {
  78. return ""
  79. }
  80. if json.Get("code").Int() == 0 {
  81. city := fmt.Sprintf("%s %s", json.Get("pro").String(), json.Get("city").String())
  82. return city
  83. } else {
  84. return ""
  85. }
  86. }