Files
go-account-register/utils/ip_request.go
2025-09-13 10:22:49 +08:00

85 lines
2.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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)
}