[fix]根据IP获取地址问题

This commit is contained in:
PandaX
2024-03-13 11:27:30 +08:00
parent 800ef60830
commit e4dbd843f2
4 changed files with 92 additions and 13 deletions

79
kit/utils/charset.go Normal file
View File

@@ -0,0 +1,79 @@
package utils
import (
"bytes"
"errors"
"fmt"
"io"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/ianaindex"
"golang.org/x/text/transform"
)
var (
// Alias for charsets.
charsetAlias = map[string]string{
"HZGB2312": "HZ-GB-2312",
"hzgb2312": "HZ-GB-2312",
"GB2312": "HZ-GB-2312",
"gb2312": "HZ-GB-2312",
}
)
func Convert(dstCharset string, srcCharset string, src string) (dst string, err error) {
if dstCharset == srcCharset {
return src, nil
}
dst = src
// Converting `src` to UTF-8.
e, err := getEncoding(srcCharset)
if err != nil {
return "", err
}
if srcCharset != "UTF-8" {
if e != nil {
tmp, err := io.ReadAll(
transform.NewReader(bytes.NewReader([]byte(src)), e.NewDecoder()),
)
if err != nil {
return "", errors.New(fmt.Sprintf(`convert string "%s" to utf8 failed`, srcCharset))
}
src = string(tmp)
} else {
return dst, errors.New(fmt.Sprintf(`unsupported srcCharset "%s"`, srcCharset))
}
}
// Do the converting from UTF-8 to `dstCharset`.
if dstCharset != "UTF-8" {
if e != nil {
tmp, err := io.ReadAll(
transform.NewReader(bytes.NewReader([]byte(src)), e.NewEncoder()),
)
if err != nil {
return "", errors.New(fmt.Sprintf(`convert string from utf8 to "%s" failed`, srcCharset))
}
dst = string(tmp)
} else {
return dst, errors.New(fmt.Sprintf(`unsupported dstCharset "%s"`, srcCharset))
}
} else {
dst = src
}
return dst, nil
}
func ToUTF8(srcCharset string, src string) (dst string, err error) {
return Convert("UTF-8", srcCharset, src)
}
func UTF8To(dstCharset string, src string) (dst string, err error) {
return Convert(dstCharset, "UTF-8", src)
}
func getEncoding(charset string) (encoding.Encoding, error) {
if c, ok := charsetAlias[charset]; ok {
charset = c
}
return ianaindex.MIB.Encoding(charset)
}

View File

@@ -6,8 +6,6 @@ import (
"pandax/kit/httpclient"
)
const ipurl = "https://ip.cn/api/index"
const UNKNOWN = "XX XX"
// GetRealAddressByIP 获取真实地址
@@ -15,17 +13,15 @@ func GetRealAddressByIP(ip string) string {
if ip == "127.0.0.1" || ip == "localhost" {
return "内部IP"
}
url := fmt.Sprintf("%s?ip=%s&type=1", ipurl, ip)
url := fmt.Sprintf("http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=%s", ip)
res := httpclient.NewRequest(url).Get()
if res == nil || res.StatusCode != 200 {
return UNKNOWN
}
toMap, err := res.BodyToMap()
if err != nil {
return UNKNOWN
}
return toMap["address"].(string)
dst, _ := ToUTF8("GBK", string(res.Body))
toMap := Json2Map(dst)
return fmt.Sprintf("%s %s", toMap["pro"].(string), toMap["city"].(string))
}
// 获取局域网ip地址

View File

@@ -12,7 +12,7 @@ func TestIdsStrToIdsIntGroup(t *testing.T) {
}
func TestGetRealAddressByIP(t *testing.T) {
ip := GetRealAddressByIP("10.42.0.1")
ip := GetRealAddressByIP("58.57.107.34")
t.Log(ip)
}