73 lines
1.4 KiB
Go
73 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
type IPInfo struct {
|
|
Msg string `json:"msg"`
|
|
Data struct {
|
|
Continent string `json:"continent"`
|
|
Country string `json:"country"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
func isValidIP(ip string) bool {
|
|
return net.ParseIP(ip) != nil
|
|
}
|
|
|
|
func main() {
|
|
if len(os.Args) < 2 {
|
|
log.Fatalf("用法: %s <IP>", os.Args[0])
|
|
}
|
|
|
|
ip := os.Args[1]
|
|
if !isValidIP(ip) {
|
|
log.Fatalf("无效的 IP 地址: %s", ip)
|
|
}
|
|
|
|
// 目标 URL
|
|
url := "https://qifu.baidu.com/ip/geo/v1/district?ip=" + ip
|
|
|
|
// 创建 HTTP 客户端并设置超时时间
|
|
client := &http.Client{Timeout: 10 * time.Second}
|
|
|
|
// 发送 GET 请求
|
|
resp, err := client.Get(url)
|
|
if err != nil {
|
|
log.Fatalf("发送 GET 请求时出错: %v", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
// 检查 HTTP 响应状态码
|
|
if resp.StatusCode != http.StatusOK {
|
|
log.Fatalf("HTTP 请求失败,状态码: %d", resp.StatusCode)
|
|
}
|
|
|
|
// 读取响应体
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
log.Fatalf("读取响应体时出错: %v", err)
|
|
}
|
|
|
|
// 解析 JSON 数据
|
|
var ipInfo IPInfo
|
|
if err := json.Unmarshal(body, &ipInfo); err != nil {
|
|
log.Fatalf("解析 JSON 时出错: %v", err)
|
|
}
|
|
|
|
if ipInfo.Msg == "查询成功" {
|
|
// 提取并打印 continent 和 country 字段
|
|
fmt.Printf("%s%s\n", ipInfo.Data.Continent, ipInfo.Data.Country)
|
|
} else {
|
|
fmt.Printf("查询失败\n")
|
|
}
|
|
}
|