85 lines
2.1 KiB
Go
85 lines
2.1 KiB
Go
package utils
|
||
|
||
import (
|
||
"fmt"
|
||
"log"
|
||
|
||
"github.com/go-resty/resty/v2"
|
||
)
|
||
|
||
type IpRequest struct {
|
||
}
|
||
|
||
type IPAPIResponse struct {
|
||
As string `json:"as"`
|
||
Asname string `json:"asname"`
|
||
City string `json:"city"`
|
||
Continent string `json:"continent"`
|
||
ContinentCode string `json:"continentCode"`
|
||
Country string `json:"country"`
|
||
CountryCode string `json:"countryCode"`
|
||
Currency string `json:"currency"`
|
||
District string `json:"district"`
|
||
Hosting bool `json:"hosting"`
|
||
Isp string `json:"isp"`
|
||
Lat float64 `json:"lat"`
|
||
Lon float64 `json:"lon"`
|
||
Mobile bool `json:"mobile"`
|
||
Offset float64 `json:"offset"`
|
||
Org string `json:"org"`
|
||
Proxy bool `json:"proxy"`
|
||
Query string `json:"query"`
|
||
Region string `json:"region"`
|
||
RegionName string `json:"regionName"`
|
||
Timezone string `json:"timezone"`
|
||
Zip string `json:"zip"`
|
||
}
|
||
|
||
func (*IpRequest) IpApi(targetIP string) (IPAPIResponse, error) {
|
||
// 创建Resty客户端
|
||
client := resty.New()
|
||
|
||
// 构建请求URL
|
||
// targetIP := "103.142.140.235"
|
||
var url string = "http://demo.ip-api.com/json?fields=66842623&lang=en"
|
||
if targetIP != "" {
|
||
url = fmt.Sprintf("http://demo.ip-api.com/json/%s?fields=66842623&lang=en", targetIP)
|
||
}
|
||
|
||
// 创建响应结构体实例
|
||
var result IPAPIResponse
|
||
|
||
// 发送GET请求(不设置任何请求头)
|
||
resp, err := client.R().
|
||
SetResult(&result). // 自动解析JSON到结构体
|
||
Get(url)
|
||
|
||
// 错误处理
|
||
if err != nil {
|
||
fmt.Printf("请求失败: %v\n", err)
|
||
return result, err
|
||
}
|
||
|
||
// 检查HTTP状态码
|
||
if resp.StatusCode() != 200 {
|
||
fmt.Printf("API返回错误状态码: %d\n", resp.StatusCode())
|
||
return result, err
|
||
}
|
||
|
||
return result, nil
|
||
}
|
||
|
||
func (*IpRequest) GetIPAddress() {
|
||
// 创建Resty客户端
|
||
client := resty.New()
|
||
var url string = "http://icanhazip.com/"
|
||
// 发送GET请求(不设置任何请求头)
|
||
resp, err := client.R().
|
||
Get(url)
|
||
// 错误处理
|
||
if err != nil {
|
||
fmt.Printf("请求失败: %v\n", err)
|
||
}
|
||
log.Println(resp)
|
||
}
|