### Install IP2Location Go Library Source: https://github.com/ip2location/ip2location-go/blob/master/docs/source/quickstart.md This command installs the IP2Location Go library using the go get command. It fetches the latest version of the library and makes it available for use in your Go projects. ```bash go get github.com/ip2location/ip2location-go/v9 ``` -------------------------------- ### Query Geolocation Data with IP2Location Go Source: https://github.com/ip2location/ip2location-go/blob/master/docs/source/quickstart.md This Go code snippet demonstrates how to open an IP2Location BIN database and query comprehensive geolocation information for a given IP address. It handles potential errors during database opening and querying, and then prints various details such as country, region, city, ISP, coordinates, and more. The code also shows how to retrieve the API version. ```go package main import ( "fmt" "github.com/ip2location/ip2location-go/v9" ) func main() { db, err := ip2location.OpenDB("./IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-ADDRESSTYPE-CATEGORY-DISTRICT-ASN.BIN") if err != nil { fmt.Print(err) return } ip := "8.8.8.8" results, err := db.Get_all(ip) if err != nil { fmt.Print(err) return } fmt.Printf("country_short: %s\n", results.Country_short) fmt.Printf("country_long: %s\n", results.Country_long) fmt.Printf("region: %s\n", results.Region) fmt.Printf("city: %s\n", results.City) fmt.Printf("isp: %s\n", results.Isp) fmt.Printf("latitude: %f\n", results.Latitude) fmt.Printf("longitude: %f\n", results.Longitude) fmt.Printf("domain: %s\n", results.Domain) fmt.Printf("zipcode: %s\n", results.Zipcode) fmt.Printf("timezone: %s\n", results.Timezone) fmt.Printf("netspeed: %s\n", results.Netspeed) fmt.Printf("iddcode: %s\n", results.Iddcode) fmt.Printf("areacode: %s\n", results.Areacode) fmt.Printf("weatherstationcode: %s\n", results.Weatherstationcode) fmt.Printf("weatherstationname: %s\n", results.Weatherstationname) fmt.Printf("mcc: %s\n", results.Mcc) fmt.Printf("mnc: %s\n", results.Mnc) fmt.Printf("mobilebrand: %s\n", results.Mobilebrand) fmt.Printf("elevation: %f\n", results.Elevation) fmt.Printf("usagetype: %s\n", results.Usagetype) fmt.Printf("addresstype: %s\n", results.Addresstype) fmt.Printf("category: %s\n", results.Category) fmt.Printf("district: %s\n", results.District) fmt.Printf("asn: %s\n", results.Asn) fmt.Printf("as: %s\n", results.As) fmt.Printf("asdomain: %s\n", results.Asdomain) fmt.Printf("asusagetype: %s\n", results.Asusagetype) fmt.Printf("ascidr: %s\n", results.Ascidr) fmt.Printf("api version: %s\n", ip2location.Api_version()) db.Close() } ``` -------------------------------- ### List Country Information Go Source: https://github.com/ip2location/ip2location-go/blob/master/docs/source/quickstart.md This Go code snippet demonstrates how to query country information using the IP2Location Country Information CSV file. It shows how to open the CSV, retrieve information for a specific country code (e.g., 'US'), and iterate through all country records. Error handling is included for file opening and data retrieval. ```go package main import ( "github.com/ip2location/ip2location-go" "fmt" ) func main() { c, err := ip2location.OpenCountryInfo("./IP2LOCATION-COUNTRY-INFORMATION.CSV") if err != nil { fmt.Print(err) return } res, err := c.GetCountryInfo("US") if err != nil { fmt.Print(err) return } fmt.Printf("country_code: %s\n", res[0].Country_code) fmt.Printf("country_name: %s\n", res[0].Country_name) fmt.Printf("country_alpha3_code: %s\n", res[0].Country_alpha3_code) fmt.Printf("country_numeric_code: %s\n", res[0].Country_numeric_code) fmt.Printf("capital: %s\n", res[0].Capital) fmt.Printf("country_demonym: %s\n", res[0].Country_demonym) fmt.Printf("total_area: %s\n", res[0].Total_area) fmt.Printf("population: %s\n", res[0].Population) fmt.Printf("idd_code: %s\n", res[0].Idd_code) fmt.Printf("currency_code: %s\n", res[0].Currency_code) fmt.Printf("currency_name: %s\n", res[0].Currency_name) fmt.Printf("currency_symbol: %s\n", res[0].Currency_symbol) fmt.Printf("lang_code: %s\n", res[0].Lang_code) fmt.Printf("lang_name: %s\n", res[0].Lang_name) fmt.Printf("cctld: %s\n", res[0].Cctld) fmt.Print("==============================================\n") res2, err := c.GetCountryInfo() if err != nil { fmt.Print(err) return } for _, v := range res2 { fmt.Printf("country_code: %s\n", v.Country_code) fmt.Printf("country_name: %s\n", v.Country_name) fmt.Printf("country_alpha3_code: %s\n", v.Country_alpha3_code) fmt.Printf("country_numeric_code: %s\n", v.Country_numeric_code) fmt.Printf("capital: %s\n", v.Capital) fmt.Printf("country_demonym: %s\n", v.Country_demonym) fmt.Printf("total_area: %s\n", v.Total_area) fmt.Printf("population: %s\n", v.Population) fmt.Printf("idd_code: %s\n", v.Idd_code) fmt.Printf("currency_code: %s\n", v.Currency_code) fmt.Printf("currency_name: %s\n", v.Currency_name) fmt.Printf("currency_symbol: %s\n", v.Currency_symbol) fmt.Printf("lang_code: %s\n", v.Lang_code) fmt.Printf("lang_name: %s\n", v.Lang_name) fmt.Printf("cctld: %s\n", v.Cctld) fmt.Print("==============================================\n") } } ``` -------------------------------- ### Convert CIDR Notation to IP Address Ranges in Go Source: https://context7.com/ip2location/ip2location-go/llms.txt This Go code snippet illustrates how to convert CIDR (Classless Inter-Domain Routing) notation back into start and end IP address ranges for both IPv4 and IPv6. It uses the ip2location-go library and provides examples for various CIDR blocks, including different network sizes and private IP ranges. The output is an array containing the start and end IP addresses. ```go package main import ( "fmt" "github.com/ip2location/ip2location-go/v9" ) func main() { tools := ip2location.OpenTools() // Convert IPv4 CIDR to range cidr4 := "192.168.1.0/24" range4, err := tools.CIDRToIPv4(cidr4) if err != nil { fmt.Println("IPv4 CIDR error:", err) return } fmt.Printf("CIDR %s:\n", cidr4) fmt.Printf(" Start: %s\n", range4[0]) fmt.Printf(" End: %s\n", range4[1]) // Various IPv4 CIDR examples testCIDRs4 := []string{ "10.0.0.0/8", // Class A network "172.16.0.0/12", // Private network "192.168.0.0/16", // Private network "8.8.8.0/29", // Small subnet } fmt.Println("\nIPv4 CIDR conversions:") for _, cidr := range testCIDRs4 { rng, err := tools.CIDRToIPv4(cidr) if err != nil { fmt.Printf(" %s: Error - %s\n", cidr, err) continue } fmt.Printf(" %-18s => %s to %s\n", cidr, rng[0], rng[1]) } // Convert IPv6 CIDR to range cidr6 := "2001:db8::/32" range6, err := tools.CIDRToIPv6(cidr6) if err != nil { fmt.Println("IPv6 CIDR error:", err) return } fmt.Printf("\nCIDR %s:\n", cidr6) fmt.Printf(" Start: %s\n", range6[0]) fmt.Printf(" End: %s\n", range6[1]) // Various IPv6 CIDR examples testCIDRs6 := []string{ "2001:db8::/48", "fe80::/10", "ff00::/8", } fmt.Println("\nIPv6 CIDR conversions:") for _, cidr := range testCIDRs6 { rng, err := tools.CIDRToIPv6(cidr) if err != nil { fmt.Printf(" %s: Error - %s\n", cidr, err) continue } fmt.Printf(" %s\n", cidr) fmt.Printf(" Start: %s\n", rng[0]) fmt.Printf(" End: %s\n", rng[1]) } } ``` -------------------------------- ### List Region Information Go Source: https://github.com/ip2location/ip2location-go/blob/master/docs/source/quickstart.md This Go code snippet demonstrates how to retrieve a region code using the IP2Location ISO 3166-2 Subdivision Code CSV file. It shows how to open the CSV file and then query for a specific region code by providing the country code and the region name. Error handling for file opening and data retrieval is included. ```go package main import ( "github.com/ip2location/ip2location-go" "fmt" ) func main() { r, err := ip2location.OpenRegionInfo("./IP2LOCATION-ISO3166-2.CSV") if err != nil { fmt.Print(err) return } res, err := r.GetRegionCode("US", "California") if err != nil { fmt.Print(err) return } fmt.Printf("region code: %s\n", res) } ``` -------------------------------- ### Process IP Addresses with IP Tools in Go Source: https://github.com/ip2location/ip2location-go/blob/master/docs/source/quickstart.md This Go code demonstrates the usage of the IP Tools class from the IP2Location library for various IP address manipulations. It includes functions to check if an IP is IPv4 or IPv6, convert IPs to and from decimal representations, compress and expand IPv6 addresses, and convert IP ranges to CIDR notation and vice-versa. Error handling is included for conversion operations. ```go package main import ( "github.com/ip2location/ip2location-go/v9" "fmt" "math/big" ) func main() { t := ip2location.OpenTools() ip := "8.8.8.8" res := t.IsIPv4(ip) fmt.Printf("Is IPv4: %t\n", res) ipnum, err := t.IPv4ToDecimal(ip) if err != nil { fmt.Print(err) } else { fmt.Printf("IPNum: %v\n", ipnum) } ip2 := "2600:1f18:45b0:5b00:f5d8:4183:7710:ceec" res2 := t.IsIPv6(ip2) fmt.Printf("Is IPv6: %t\n", res2) ipnum2, err := t.IPv6ToDecimal(ip2) if err != nil { fmt.Print(err) } else { fmt.Printf("IPNum: %v\n", ipnum2) } ipnum3 := big.NewInt(42534) res3, err := t.DecimalToIPv4(ipnum3) if err != nil { fmt.Print(err) } else { fmt.Printf("IPv4: %v\n", res3) } ipnum4, ok := big.NewInt(0).SetString("22398978840339333967292465152", 10) if ok { res4, err := t.DecimalToIPv6(ipnum4) if err != nil { fmt.Print(err) } else { fmt.Printf("IPv6: %v\n", res4) } } ip3 := "2600:1f18:045b:005b:f5d8:0:000:ceec" res5, err := t.CompressIPv6(ip3) if err != nil { fmt.Print(err) } else { fmt.Printf("Compressed: %v\n", res5) } ip4 := "::45b:05b:f5d8:0:000:ceec" res6, err := t.ExpandIPv6(ip4) if err != nil { fmt.Print(err) } else { fmt.Printf("Expanded: %v\n", res6) } res7, err := t.IPv4ToCIDR("10.0.0.0", "10.10.2.255") if err != nil { fmt.Print(err) } else { for _, element := range res7 { fmt.Println(element) } } res8, err := t.IPv6ToCIDR("2001:4860:4860:0000:0000:0000:0000:8888", "2001:4860:4860:0000:eeee:ffff:ffff:ffff") if err != nil { fmt.Print(err) } else { for _, element := range res8 { fmt.Println(element) } } res9, err := t.CIDRToIPv4("123.245.99.13/26") if err != nil { fmt.Print(err) } else { fmt.Printf("IPv4 Range: %v\n", res9) } res10, err := t.CIDRToIPv6("2002:1234::abcd:ffff:c0a8:101/62") if err != nil { fmt.Print(err) } else { fmt.Printf("IPv6 Range: %v\n", res10) } } ``` -------------------------------- ### Get IP2Location Go Database Version Information Source: https://context7.com/ip2location/ip2location-go/llms.txt Retrieves and prints the IP2Location Go API version, the database package type (e.g., DB11), and the database build version. It requires the 'ip2location-go/v9' package and a valid path to the IP2Location BIN database file. The output includes the API version, database type, and database build date, along with a verification query. ```go package main import ( "fmt" "github.com/ip2location/ip2location-go/v9" ) func main() { // Get API version apiVersion := ip2location.Api_version() fmt.Printf("IP2Location Go API Version: %s\n", apiVersion) // Open database db, err := ip2location.OpenDB("/path/to/IP2LOCATION-DB11.BIN") if err != nil { fmt.Println("Error opening database:", err) return } defer db.Close() // Get database package version (database type) packageVersion := db.PackageVersion() fmt.Printf("Database Package Type: DB%s\n", packageVersion) // Get database version (build date) databaseVersion := db.DatabaseVersion() fmt.Printf("Database Version: %s\n", databaseVersion) // Use version info for validation if packageVersion == "11" { fmt.Println("This is DB11 - includes all standard geolocation fields") } // Combined version check fmt.Printf("\nDatabase Info:\n") fmt.Printf(" API: v%s\n", apiVersion) fmt.Printf(" Type: DB%s\n", packageVersion) fmt.Printf(" Date: %s\n", databaseVersion) // Perform a query to verify database is working result, err := db.Get_country_short("8.8.8.8") if err != nil { fmt.Println("Query error:", err) return } fmt.Printf("\nVerification query (8.8.8.8): %s\n", result.Country_short) } ``` -------------------------------- ### Get Geolocation Information by IP Address in Go Source: https://github.com/ip2location/ip2location-go/blob/master/docs/source/code.md Retrieves comprehensive geolocation information for a given IP address (IPv4 or IPv6). This function requires a loaded IP2Location database and returns an array containing various details such as country, region, city, ISP, and more. Refer to the documentation for a complete list of returned fields. ```Go package main import ( "fmt" "github.com/ip2location/ip2location-go/v9" ) func main() { db, err := ip2location.OpenDB("/path/to/your/IP2LOCATION-LITE.BIN") if err != nil { fmt.Println(err) return } // Example for IPv4 ipAddressV4 := "8.8.8.8" resultsV4, err := db.Get_all(ipAddressV4) if err != nil { fmt.Printf("Error getting geolocation for %s: %v\n", ipAddressV4, err) } else { fmt.Printf("Geolocation for %s:\n", ipAddressV4) fmt.Printf(" Country: %s (%s)\n", resultsV4.Country_long, resultsV4.Country_short) fmt.Printf(" City: %s\n", resultsV4.City) fmt.Printf(" ISP: %s\n", resultsV4.Isp) } // Example for IPv6 (if your database supports it) ipAddressV6 := "2001:4860:4860::8888" resultsV6, err := db.Get_all(ipAddressV6) if err != nil { fmt.Printf("Error getting geolocation for %s: %v\n", ipAddressV6, err) } else { fmt.Printf("Geolocation for %s:\n", ipAddressV6) fmt.Printf(" Country: %s (%s)\n", resultsV6.Country_long, resultsV6.Country_short) fmt.Printf(" City: %s\n", resultsV6.City) fmt.Printf(" ISP: %s\n", resultsV6.Isp) } } ``` -------------------------------- ### Local Database Geolocation Query with IP2Location Go Source: https://context7.com/ip2location/ip2location-go/llms.txt Demonstrates how to open an IP2Location BIN database file and perform geolocation lookups for IPv4 and IPv6 addresses. It covers querying all available fields and specific fields like city. Requires the IP2Location BIN database file and the ip2location-go/v9 package. ```go package main import ( "fmt" "github.com/ip2location/ip2location-go/v9" ) func main() { // Open the database file db, err := ip2location.OpenDB("/path/to/IP2LOCATION-DB11.BIN") if err != nil { fmt.Println("Error opening database:", err) return } defer db.Close() // Query all available fields for an IPv4 address result, err := db.Get_all("8.8.8.8") if err != nil { fmt.Println("Query error:", err) return } // Print results fmt.Printf("Country: %s (%s)\n", result.Country_long, result.Country_short) fmt.Printf("Region: %s\n", result.Region) fmt.Printf("City: %s\n", result.City) fmt.Printf("Coordinates: %.4f, %.4f\n", result.Latitude, result.Longitude) fmt.Printf("ISP: %s\n", result.Isp) fmt.Printf("Timezone: %s\n", result.Timezone) // Query IPv6 address result6, err := db.Get_all("2001:4860:4860::8888") if err != nil { fmt.Println("IPv6 query error:", err) return } fmt.Printf("IPv6 Country: %s\n", result6.Country_short) // Query specific fields only cityResult, err := db.Get_city("1.2.3.4") if err != nil { fmt.Println("City query error:", err) return } fmt.Printf("City only: %s\n", cityResult.City) } ``` -------------------------------- ### Load IP2Location Database in Go Source: https://github.com/ip2location/ip2location-go/blob/master/docs/source/code.md Loads the IP2Location BIN database for subsequent IP address lookups. Requires the file path to the database as input. This function initializes the necessary data structures for geolocation queries. ```Go package main import ( "fmt" "github.com/ip2location/ip2location-go/v9" ) func main() { db, err := ip2location.OpenDB("/path/to/your/IP2LOCATION-LITE.BIN") if err != nil { fmt.Println(err) return } results, err := db.Get_all("8.8.8.8") if err != nil { fmt.Println(err) return } fmt.Printf("Country Short: %s\n", results.Country_short) fmt.Printf("Country Long: %s\n", results.Country_long) fmt.Printf("Region: %s\n", results.Region) fmt.Printf("City: %s\n", results.City) fmt.Printf("ISP: %s\n", results.Isp) fmt.Printf("Latitude: %f\n", results.Latitude) fmt.Printf("Longitude: %f\n", results.Longitude) fmt.Printf("Domain: %s\n", results.Domain) fmt.Printf("ZipCode: %s\n", results.ZipCode) fmt.Printf("TimeZone: %s\n", results.Timezone) fmt.Printf("Netspeed: %s\n", results.Netspeed) fmt.Printf("IDDCode: %s\n", results.Iddcode) fmt.Printf("AreaCode: %s\n", results.Areacode) fmt.Printf("Weatherstationcode: %s\n", results.Weatherstationcode) fmt.Printf("Weatherstationname: %s\n", results.Weatherstationname) fmt.Printf("MCC: %s\n", results.Mcc) fmt.Printf("MNC: %s\n", results.Mnc) fmt.Printf("Mobilebrand: %s\n", results.Mobilebrand) fmt.Printf("Elevation: %d\n", results.Elevation) fmt.Printf("UsageType: %s\n", results.Usagetype) fmt.Printf("AddressType: %s\n", results.Addresstype) fmt.Printf("Category: %s\n", results.Category) fmt.Printf("District: %s\n", results.District) fmt.Printf("ASN: %s\n", results.Asn) fmt.Printf("AS: %s\n", results.AS) fmt.Printf("ASDomain: %s\n", results.Asdomain) fmt.Printf("ASUsageType: %s\n", results.Asusagetype) fmt.Printf("ASCIDR: %s\n", results.Ascidr) } ``` -------------------------------- ### Web Service Geolocation Query with IP2Location Go Source: https://context7.com/ip2location/ip2location-go/llms.txt Illustrates how to use the IP2Location cloud web service client to perform real-time geolocation lookups. It supports various addons like continent and country data, and checks the remaining credit balance. Requires an API key and the ip2location-go/v9 package. ```go package main import ( "fmt" "github.com/ip2location/ip2location-go/v9" ) func main() { // Initialize web service client ws, err := ip2location.OpenWS("YOUR_API_KEY", "WS10", true) if err != nil { fmt.Println("Error initializing web service:", err) return } // Perform lookup with optional addons (continent, country, geotargeting) result, err := ws.LookUp("8.8.8.8", "continent,country", "") if err != nil { fmt.Println("Lookup error:", err) return } // Check response status if result.Response != "OK" { fmt.Println("API returned error:", result.Response) return } // Access basic geolocation data fmt.Printf("Country: %s (%s)\n", result.CountryName, result.CountryCode) fmt.Printf("Region: %s\n", result.RegionName) fmt.Printf("City: %s\n", result.CityName) fmt.Printf("Coordinates: %.6f, %.6f\n", result.Latitude, result.Longitude) fmt.Printf("Time Zone: %s\n", result.TimeZone) // Access extended country information (with country addon) fmt.Printf("Capital: %s\n", result.Country.Capital) fmt.Printf("Currency: %s (%s)\n", result.Country.Currency.Name, result.Country.Currency.Code) fmt.Printf("Language: %s\n", result.Country.Language.Name) fmt.Printf("Population: %s\n", result.Country.Population) // Access continent information (with continent addon) fmt.Printf("Continent: %s (%s)\n", result.Continent.Name, result.Continent.Code) // Check credit balance credit, err := ws.GetCredit() if err != nil { fmt.Println("Credit check error:", err) return } fmt.Printf("Remaining credits: %d\n", credit.Response) } ``` -------------------------------- ### Compress and Expand IPv6 Addresses (Go) Source: https://context7.com/ip2location/ip2location-go/llms.txt Provides functionality to compress long IPv6 addresses into their shortest, valid representation and to expand compressed IPv6 addresses into their full, unabbreviated form. Handles various standard IPv6 formats. Uses 'github.com/ip2location/ip2location-go/v9'. ```go package main import ( "fmt" "github.com/ip2location/ip2location-go/v9" ) func main() { tools := ip2location.OpenTools() // Compress IPv6 address longIPv6 := "2001:0db8:0000:0000:0000:0000:0000:0001" compressed, err := tools.CompressIPv6(longIPv6) if err != nil { fmt.Println("Compression error:", err) return } fmt.Printf("Long form: %s\n", longIPv6) fmt.Printf("Compressed form: %s\n", compressed) // Expand IPv6 address shortIPv6 := "2001:db8::1" expanded, err := tools.ExpandIPv6(shortIPv6) if err != nil { fmt.Println("Expansion error:", err) return } fmt.Printf("Short form: %s\n", shortIPv6) fmt.Printf("Expanded form: %s\n", expanded) // Handle various IPv6 formats testAddresses := []string{ "::1", // loopback "fe80::1", // link-local "2001:db8::8a2e:370:7334", // documentation "::ffff:192.0.2.1", // IPv4-mapped } for _, addr := range testAddresses { expanded, _ := tools.ExpandIPv6(addr) compressed, _ := tools.CompressIPv6(addr) fmt.Printf("Original: %-30s Expanded: %s\n", addr, expanded) fmt.Printf("%-" + "40s" + " Compressed: %s\n", "", compressed) } } ``` -------------------------------- ### Convert IP Address Ranges to CIDR Notation in Go Source: https://context7.com/ip2location/ip2location-go/llms.txt This Go code snippet demonstrates how to convert IPv4 and IPv6 address ranges into CIDR (Classless Inter-Domain Routing) notation. It utilizes the ip2location-go library and handles both contiguous and non-contiguous IP ranges. The output is a list of CIDR strings. ```go package main import ( "fmt" "github.com/ip2location/ip2location-go/v9" ) func main() { tools := ip2location.OpenTools() // Convert IPv4 range to CIDR ipv4Start := "10.0.0.0" ipv4End := "10.0.0.255" cidrs4, err := tools.IPv4ToCIDR(ipv4Start, ipv4End) if err != nil { fmt.Println("IPv4 range to CIDR error:", err) return } fmt.Printf("IPv4 range %s - %s:\n", ipv4Start, ipv4End) for _, cidr := range cidrs4 { fmt.Printf(" %s\n", cidr) } // Convert non-contiguous IPv4 range ipv4Start2 := "192.168.1.10" ipv4End2 := "192.168.1.50" cidrs4b, err := tools.IPv4ToCIDR(ipv4Start2, ipv4End2) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("\nIPv4 range %s - %s:\n", ipv4Start2, ipv4End2) for _, cidr := range cidrs4b { fmt.Printf(" %s\n", cidr) } // Convert IPv6 range to CIDR ipv6Start := "2001:db8::" ipv6End := "2001:db8::ffff" cidrs6, err := tools.IPv6ToCIDR(ipv6Start, ipv6End) if err != nil { fmt.Println("IPv6 range to CIDR error:", err) return } fmt.Printf("\nIPv6 range %s - %s:\n", ipv6Start, ipv6End) for _, cidr := range cidrs6 { fmt.Printf(" %s\n", cidr) } } ``` -------------------------------- ### Convert IPs to Decimal and Vice Versa (Go) Source: https://context7.com/ip2location/ip2location-go/llms.txt Converts IPv4 and IPv6 addresses to their decimal (big.Int) representations and converts decimal values back to IP addresses. This is useful for network calculations and comparisons. Depends on 'github.com/ip2location/ip2location-go/v9' and 'math/big'. ```go package main import ( "fmt" "math/big" "github.com/ip2location/ip2location-go/v9" ) func main() { tools := ip2location.OpenTools() // IPv4 conversions ipv4 := "192.168.1.100" decimal4, err := tools.IPv4ToDecimal(ipv4) if err != nil { fmt.Println("IPv4 to decimal error:", err) return } fmt.Printf("IPv4 %s = %s (decimal)\n", ipv4, decimal4.String()) // Convert back to IPv4 backToIP4, err := tools.DecimalToIPv4(decimal4) if err != nil { fmt.Println("Decimal to IPv4 error:", err) return } fmt.Printf("Decimal %s = %s (IPv4)\n", decimal4.String(), backToIP4) // IPv6 conversions ipv6 := "2001:0db8:85a3:0000:0000:8a2e:0370:7334" decimal6, err := tools.IPv6ToDecimal(ipv6) if err != nil { fmt.Println("IPv6 to decimal error:", err) return } fmt.Printf("IPv6 %s = %s (decimal)\n", ipv6, decimal6.String()) // Convert back to IPv6 backToIP6, err := tools.DecimalToIPv6(decimal6) if err != nil { fmt.Println("Decimal to IPv6 error:", err) return } fmt.Printf("Decimal %s = %s (IPv6)\n", decimal6.String(), backToIP6) // Working with specific decimal values customDecimal := big.NewInt(3232235876) // 192.168.1.100 customIP, _ := tools.DecimalToIPv4(customDecimal) fmt.Printf("Custom decimal %d = %s\n", customDecimal.Int64(), customIP) } ``` -------------------------------- ### Go Country Information Lookup Source: https://context7.com/ip2location/ip2location-go/llms.txt Retrieves detailed country information using the IP2Location Go library. It requires opening a CSV database file and accepts country codes as input. Outputs include various country-specific details and can fetch all country records. ```go package main import ( "fmt" "github.com/ip2location/ip2location-go/v9" ) func main() { // Open country information CSV file ci, err := ip2location.OpenCountryInfo("/path/to/IP2LOCATION-COUNTRY-INFORMATION.CSV") if err != nil { fmt.Println("Error opening country info:", err) return } // Get information for a specific country records, err := ci.GetCountryInfo("US") if err != nil { fmt.Println("Query error:", err) return } if len(records) > 0 { rec := records[0] fmt.Printf("Country Code: %s\n", rec.Country_code) fmt.Printf("Country Name: %s\n", rec.Country_name) fmt.Printf("Alpha3 Code: %s\n", rec.Country_alpha3_code) fmt.Printf("Numeric Code: %s\n", rec.Country_numeric_code) fmt.Printf("Capital: %s\n", rec.Capital) fmt.Printf("Demonym: %s\n", rec.Country_demonym) fmt.Printf("Total Area: %s sq km\n", rec.Total_area) fmt.Printf("Population: %s\n", rec.Population) fmt.Printf("IDD Code: %s\n", rec.Idd_code) fmt.Printf("Currency: %s (%s) %s\n", rec.Currency_name, rec.Currency_code, rec.Currency_symbol) fmt.Printf("Language: %s (%s)\n", rec.Lang_name, rec.Lang_code) fmt.Printf("ccTLD: %s\n", rec.Cctld) } // Get all countries allCountries, err := ci.GetCountryInfo() if err != nil { fmt.Println("Error getting all countries:", err) return } fmt.Printf("\nTotal countries in database: %d\n", len(allCountries)) // Iterate through multiple countries countryCodes := []string{"GB", "JP", "AU", "DE", "FR"} for _, code := range countryCodes { records, err := ci.GetCountryInfo(code) if err == nil && len(records) > 0 { fmt.Printf("%s: %s (Capital: %s)\n", records[0].Country_code, records[0].Country_name, records[0].Capital) } } } ``` -------------------------------- ### Validate IP Addresses and Detect Type (Go) Source: https://context7.com/ip2location/ip2location-go/llms.txt Validates if a given string is a valid IPv4 or IPv6 address and determines its type. It can also convert valid IPs to their decimal representation. Requires the 'github.com/ip2location/ip2location-go/v9' package. ```go package main import ( "fmt" "github.com/ip2location/ip2location-go/v9" ) func main() { tools := ip2location.OpenTools() // Test various IP addresses testIPs := []string{ "8.8.8.8", "192.168.1.1", "2001:4860:4860::8888", "::1", "not-an-ip", } for _, ip := range testIPs { fmt.Printf("\nTesting: %s\n", ip) if tools.IsIPv4(ip) { fmt.Println(" Type: IPv4") decimal, err := tools.IPv4ToDecimal(ip) if err != nil { fmt.Println(" Error:", err) } else { fmt.Printf(" Decimal: %s\n", decimal.String()) } } else if tools.IsIPv6(ip) { fmt.Println(" Type: IPv6") decimal, err := tools.IPv6ToDecimal(ip) if err != nil { fmt.Println(" Error:", err) } else { fmt.Printf(" Decimal: %s\n", decimal.String()) } } else { fmt.Println(" Type: Invalid IP address") } } } ``` -------------------------------- ### Go Region Information Lookup Source: https://context7.com/ip2location/ip2location-go/llms.txt Retrieves region codes from a CSV database using the IP2Location Go library. It requires opening a CSV database file and accepts country and region names as input. This function supports case-insensitive lookups and can query multiple regions. ```go package main import ( "fmt" "github.com/ip2location/ip2location-go/v9" ) func main() { // Open region information CSV file ri, err := ip2location.OpenRegionInfo("/path/to/IP2LOCATION-REGION-INFORMATION.CSV") if err != nil { fmt.Println("Error opening region info:", err) return } // Get region code for a specific country and region name regionCode, err := ri.GetRegionCode("US", "California") if err != nil { fmt.Println("Query error:", err) return } fmt.Printf("Region: California, USA\n") fmt.Printf("Region Code: %s\n", regionCode) // Look up multiple regions type RegionQuery struct { Country string Region string } queries := []RegionQuery{ {"US", "New York"}, {"US", "Texas"}, {"GB", "England"}, {"AU", "New South Wales"}, {"JP", "Tokyo"}, } fmt.Println("\nRegion Code Lookups:") for _, query := range queries { code, err := ri.GetRegionCode(query.Country, query.Region) if err != nil { fmt.Printf(" %s, %s: Not found\n", query.Region, query.Country) } else { fmt.Printf(" %s, %s: %s\n", query.Region, query.Country, code) } } // Case-insensitive lookup codeUpper, _ := ri.GetRegionCode("US", "CALIFORNIA") codeLower, _ := ri.GetRegionCode("US", "california") codeMixed, _ := ri.GetRegionCode("US", "CaLiFoRnIa") fmt.Printf("\nCase-insensitive lookup demonstration:\n") fmt.Printf(" CALIFORNIA: %s\n", codeUpper) fmt.Printf(" california: %s\n", codeLower) fmt.Printf(" CaLiFoRnIa: %s\n", codeMixed) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.