go语言实现IP归属地查询

效果:

实现代码main.go

Go 复制代码
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
)

type AreaData struct {
	Continent string `json:"continent"`
	Country   string `json:"country"`
	ZipCode   string `json:"zipcode"`
	Owner     string `json:"owner"`
	Isp       string `json:"isp"`
	Adcode    string `json:"adcode"`
	Prov      string `json:"prov"`
	City      string `json:"city"`
	District  string `json:"district"`
}

type IpData struct {
	Code string   `json:"code"`
	Data AreaData `json:"data"`
	Ip   string   `json:"ip"`
}

func main() {
	var args = os.Args
	if len(args) > 1 {
		for index, val := range args {
			if index > 0 {
				fmt.Printf("parsms[%d]: %s\n", index, val)
			}
		}
	} else {
		fmt.Println("no args ip address to check exp: ./checkip 14.23.36.151")
		return
	}

	//ip := "14.23.36.151"
	url := fmt.Sprintf("https://qifu-api.baidubce.com/ip/geo/v1/district?ip=%s", args[1])
	resp, err := http.Get(url)
	if err != nil {
		fmt.Printf("Error making request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Error reading response body: %v\n", err)
		return
	}

	var ipInfo IpData
	err = json.Unmarshal(body, &ipInfo)
	if err != nil {
		fmt.Printf("Error parsing JSON: %v\n", err)
		return
	}

	fmt.Printf("Code: %s\n", ipInfo.Code)
	fmt.Printf("Ip: %s\n", ipInfo.Ip)
	fmt.Printf("Continent: %s\n", ipInfo.Data.Continent)
	fmt.Printf("Country: %s\n", ipInfo.Data.Country)
	fmt.Printf("ZipCode: %s\n", ipInfo.Data.ZipCode)
	fmt.Printf("Owner: %s\n", ipInfo.Data.Owner)
	fmt.Printf("Isp: %s\n", ipInfo.Data.Isp)
	fmt.Printf("Adcode: %s\n", ipInfo.Data.Adcode)
	fmt.Printf("Prov: %s\n", ipInfo.Data.Prov)
	fmt.Printf("City: %s\n", ipInfo.Data.City)
	fmt.Printf("District: %s\n", ipInfo.Data.District)
}
相关推荐
风逸hhh1 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮1 小时前
Python训练第四十三天
开发语言·python
ascarl20102 小时前
准确--k8s cgroup问题排查
java·开发语言
fpcc3 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
莱茵菜苗3 小时前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长3 小时前
Python 构建法律DeepSeek RAG
开发语言·python
luojiaao3 小时前
【Python工具开发】k3q_arxml 简单但是非常好用的arxml编辑器,可以称为arxml杀手包
开发语言·python·编辑器
终焉代码3 小时前
STL解析——list的使用
开发语言·c++
SoFlu软件机器人4 小时前
智能生成完整 Java 后端架构,告别手动编写 ControllerServiceDao
java·开发语言·架构
英英_4 小时前
视频爬虫的Python库
开发语言·python·音视频