To determine the usage type of an IP address using IP2Location.io in Go, you can use the IP2Location.io API to retrieve geolocation and related data. The usage type field specifies how the IP is being used. For usage types supported, please see API documentation for more info.
go mod init example
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
type ResultObj struct {
UsageType string `json:"usage_type"`
}
type ErrorObj struct {
Error struct {
ErrorMessage string `json:"error_message"`
} `json:"error"`
}
func main() {
var res ResultObj
var ex ErrorObj
var key = "YOUR_API_KEY"
var ip = "8.8.8.8"
myUrl := "https://api.ip2location.io?format=json&ip=" + ip + "&key=" + key
resp, err := http.Get(myUrl)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
bodyStr := string(bodyBytes[:])
if strings.Contains(bodyStr, "usage_type") {
err = json.Unmarshal(bodyBytes, &res)
if err != nil {
panic(err)
}
fmt.Print("The usage type for IP " + ip + " is " + res.UsageType + ".")
} else {
panic("ERROR: The usage_type field requires a paid subscription to the Starter plan or higher.")
}
} else if resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusUnauthorized {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
bodyStr := string(bodyBytes[:])
if strings.Contains(bodyStr, "error_message") {
err = json.Unmarshal(bodyBytes, &ex)
if err != nil {
panic(err)
}
panic("ERROR: " + ex.Error.ErrorMessage)
}
} else {
panic("ERROR: Unable to call the API.")
}
}
go run example.go
This script will output the usage type of specified IP address. Make sure to replace 8.8.8.8 with the IP address you want and replace YOUR_API_KEY to your own API key.
Empower your applications with accurate IP geolocation information now.
Try It for Free