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)
}
相关推荐
爱吃烤鸡翅的酸菜鱼13 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
心情好的小球藻1 小时前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
古月-一个C++方向的小白6 小时前
C++11之lambda表达式与包装器
开发语言·c++
沐知全栈开发7 小时前
Eclipse 生成 jar 包
开发语言
杭州杭州杭州8 小时前
Python笔记
开发语言·笔记·python
tanyongxi668 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++
阿葱(聪)9 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes
浮生带你学Java10 小时前
2025Java面试题及答案整理( 2025年 7 月最新版,持续更新)
java·开发语言·数据库·面试·职场和发展