1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| package main
import ( "encoding/json" "fmt" "net/http" )
type LocationInfo struct { Status string `json:"status"` Country string `json:"country"` Region string `json:"regionName"` City string `json:"city"` ZipCode string `json:"zip"` ISP string `json:"isp"` IPAddress string `json:"query"` }
func main() { ipAddress := "8.8.8.8"
apiURL := fmt.Sprintf("http://ip-api.com/json/%s", ipAddress)
resp, err := http.Get(apiURL) if err != nil { fmt.Println("HTTP请求失败:", err) return } defer resp.Body.Close()
var location LocationInfo err = json.NewDecoder(resp.Body).Decode(&location) if err != nil { fmt.Println("JSON解析失败:", err) return }
if location.Status == "success" { fmt.Printf("IP地址: %s\n", location.IPAddress) fmt.Printf("国家: %s\n", location.Country) fmt.Printf("地区: %s\n", location.Region) fmt.Printf("城市: %s\n", location.City) fmt.Printf("邮政编码: %s\n", location.ZipCode) fmt.Printf("ISP: %s\n", location.ISP) } else { fmt.Println("无法获取IP地址信息") } }
|