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)
}
相关推荐
2401_894828125 分钟前
从原理到实战:随机森林算法全解析(附 Python 完整代码)
开发语言·python·算法·随机森林
玄同7656 分钟前
Python「焚诀」:吞噬所有语法糖的终极修炼手册
开发语言·数据库·人工智能·python·postgresql·自然语言处理·nlp
羽翼.玫瑰7 分钟前
关于重装Python失败(本质是未彻底卸载Python)的问题解决方案综述
开发语言·python
源代码•宸21 分钟前
Leetcode—509. 斐波那契数【简单】
经验分享·算法·leetcode·面试·golang·记忆化搜索·动规
CRMEB系统商城37 分钟前
CRMEB多商户系统(PHP)- 移动端二开之基本容器组件使用
运维·开发语言·小程序·php
淮北49441 分钟前
科研绘图工具R语言
开发语言·r语言
逍遥德1 小时前
java Map Set List 扩容机制
java·开发语言·list
2501_944521591 小时前
Flutter for OpenHarmony 微动漫App实战:图片加载实现
android·开发语言·前端·javascript·flutter·php
nbsaas-boot1 小时前
基于 Java 21 ScopedValue 的多租户动态数据源完整实践
java·开发语言
liuc03171 小时前
Java项目关于不同key的读取
java·开发语言