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)
}
相关推荐
gopher95111 小时前
RUST:序列化与反序列化 serde + derive 详解
开发语言·后端·rust
H.莓飛1 小时前
【Linux】自主 Shell
linux·运维·服务器·c语言·开发语言·visual studio
熊猫钓鱼>_>1 小时前
Kotlin Multiplatform for OpenHarmony 实战:kotlinx-coroutines 结构化并发适配
开发语言·kotlin·agent·harmonyos·openharmony·适配·华为云码道
沫璃染墨2 小时前
《Qt从零入门系列(十四):QThread多线程详解——从线程创建到客户端阻塞处理》
开发语言·c++·笔记·qt·ui·交互·线程
hixiong1232 小时前
C# 使用 ZXingCpp.Angle 进行条码、二维码识别
开发语言·c#·扫码
云和数据.ChenGuang2 小时前
AI 工程师相关就业岗位(细分,偏工程落地,由底层到上层)
服务器·开发语言·人工智能·python
爱读书的小胖2 小时前
Codewars:Last digit of a large number(C)解题分析
c语言·开发语言·r语言
码途行者2 小时前
处理超时未支付订单:两套轻量化方案,附 PHP 极简实现
开发语言·redis·php
云和数据.ChenGuang2 小时前
LangChain 实战指南:从入门到构建智能应用
开发语言·人工智能·python·langchain
const_qiu2 小时前
第三章 04:3.6 基础调用链的构建
开发语言·python