IP-Sonar Go Example
Fetch IP Geolocation data with Go
Example
Section titled “Example”This example demonstrates how to use the IP-Sonar API to fetch geolocation data for a given IP address using Go.
package main
import ( "encoding/json" "fmt" "io" "net/http" "time")
// IPResponse represents the structure of the response from the IP APItype IPResponse struct { IP string `json:"ip"` CountryCode string `json:"country_code"` // Add other fields as needed based on the API response}
func main() { // IP address to look up ipToLookup := "8.8.8.8" // Example IP (Google's DNS)
// Create a new HTTP client with a timeout client := &http.Client{ Timeout: 10 * time.Second, }
// Create a new request to the IP-Sonar API with the IP in the path url := fmt.Sprintf("https://api.ip-sonar.com/v1/%s", ipToLookup) req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Println("Error creating request:", err) return }
// Add headers - uncomment and replace with your actual API key if needed // req.Header.Set("X-Api-Key", "your-api-key-here")
// Send the request resp, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer resp.Body.Close()
// Check if the request was successful if resp.StatusCode != http.StatusOK { fmt.Printf("HTTP error! Status: %d\n", resp.StatusCode) return }
// Read the response body body, err := io.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading response body:", err) return }
// Parse the JSON response var ipData IPResponse err = json.Unmarshal(body, &ipData) if err != nil { fmt.Println("Error parsing JSON:", err) return }
// Display the IP information fmt.Println("IP address:", ipData.IP) fmt.Println("Country code:", ipData.CountryCode)}