Files
proxy/client/geo/cip.go

58 lines
1.4 KiB
Go

package geo
import (
"bufio"
"github.com/pkg/errors"
"log/slog"
"net/http"
"net/textproto"
"strings"
)
func Cip() (prov, city, isp string, err error) {
const endpoint = "http://cip.cc"
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return "", "", "", errors.Wrap(err, "创建请求失败")
}
req.Header.Set("User-Agent", "curl/8.9.1")
req.Header.Set("Accept", "*/*")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", "", "", errors.Wrap(err, "请求失败")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", "", "", errors.New("请求失败,状态码: " + resp.Status)
}
reader := textproto.NewReader(bufio.NewReader(resp.Body))
_, err = reader.ReadLine()
if err != nil {
return "", "", "", errors.Wrap(err, "读取响应失败")
}
addrLine, err := reader.ReadLine()
if err != nil {
return "", "", "", errors.Wrap(err, "读取响应失败")
}
addr := strings.Split(strings.Split(addrLine, ":")[1], " ")
prov = strings.TrimSpace(addr[1])
city = strings.TrimSpace(addr[2])
ispLine, err := reader.ReadLine()
if err != nil {
return "", "", "", errors.Wrap(err, "读取响应失败")
}
isp = strings.TrimSpace(strings.Split(ispLine, ":")[1])
if prov == "" || city == "" || isp == "" {
return "", "", "", errors.New("解析数据为空")
}
slog.Debug("获取归属地", "prov", prov, "city", city, "isp", isp)
return prov, city, isp, nil
}