IPGeolocation.io Go SDK


Overview

Official Go SDK for the IPGeolocation.io IP Geolocation API.

Look up IPv4, IPv6, and domains with /v3/ipgeo and /v3/ipgeo-bulk. Get geolocation, company, ASN, time zone, network, hostname, abuse, user-agent, and security data from one API.

  • Go module with v2 import path
  • Typed responses plus raw JSON and XML methods
  • Built on the Go standard library

Install

go get github.com/IPGeolocation/ip-geolocation-go-sdk/v2
import ipgeolocation "github.com/IPGeolocation/ip-geolocation-go-sdk/v2"

Go module: github.com/IPGeolocation/ip-geolocation-go-sdk/v2 Package page: https://pkg.go.dev/github.com/IPGeolocation/ip-geolocation-go-sdk/v2 GitHub repository: https://github.com/IPGeolocation/ip-geolocation-go-sdk


Quick Start

package main

import (
	"context"
	"fmt"
	"os"

	ipgeolocation "github.com/IPGeolocation/ip-geolocation-go-sdk/v2"
)

func main() {
	apiKey := os.Getenv("IPGEO_API_KEY")
	if apiKey == "" {
		panic("set IPGEO_API_KEY first")
	}

	client, err := ipgeolocation.NewClient(&ipgeolocation.Config{
		APIKey: apiKey,
	})
	if err != nil {
		panic(err)
	}
	defer client.Close()

	response, err := client.LookupIPGeolocation(context.Background(), &ipgeolocation.LookupRequest{
		IP: "8.8.8.8",
	})
	if err != nil {
		panic(err)
	}

	data := response.Data

	if data.IP != nil {
		fmt.Println(*data.IP) // 8.8.8.8
	}

	if data.Location != nil && data.Location.CountryName != nil {
		fmt.Println(*data.Location.CountryName) // United States
	}

	if data.Location != nil && data.Location.City != nil {
		fmt.Println(*data.Location.City)
	}

	if data.TimeZone != nil && data.TimeZone.Name != nil {
		fmt.Println(*data.TimeZone.Name)
	}

	if response.Metadata.CreditsCharged != nil {
		fmt.Println(*response.Metadata.CreditsCharged)
	}
}

At a Glance

ItemValue
Modulegithub.com/IPGeolocation/ip-geolocation-go-sdk/v2
Packageipgeolocation
Supported Endpoints/v3/ipgeo, /v3/ipgeo-bulk
Supported InputsIPv4, IPv6, domain
Main Data ReturnedGeolocation, company, ASN, time zone, network, hostname, abuse, user-agent, currency, security
AuthenticationAPI key
Response FormatsStructured JSON, raw JSON, raw XML
Bulk LimitUp to 50,000 IPs or domains per request
TransportGo standard library net/http

Get Your API Key

Create an IPGeolocation.io account and copy an API key from your dashboard.

  1. Sign up: https://app.ipgeolocation.io/signup
  2. Verify your email if prompted
  3. Sign in: https://app.ipgeolocation.io/login
  4. Open your dashboard: https://app.ipgeolocation.io/dashboard
  5. Copy an API key from the API Keys section

Keep your IPGeolocation.io API key in an environment variable or secret manager.


Authentication


1. API Key

client, err := ipgeolocation.NewClient(&ipgeolocation.Config{
	APIKey: os.Getenv("IPGEO_API_KEY"),
})

The API key is sent as the apiKey query parameter, so avoid logging full request URLs.


Plan Behavior

Feature availability depends on your plan and request parameters.

CapabilityFreePaid
Single IPv4 and IPv6 lookupSupportedSupported
Domain lookupNot supportedSupported
Bulk lookupNot supportedSupported
Non-English langNot supportedSupported
Optional modules via includeNot supportedSupported
include: ["*"]Base response onlyAll plan-available modules

Paid plans still need the include parameter for optional modules. fields and excludes only trim the response. They do not turn modules on or unlock paid data.


Client Configuration

FieldTypeDefaultNotes
APIKeystringunsetYour IPGeolocation.io API key.
BaseURLstringhttps://api.ipgeolocation.ioUse the final address of your API or proxy. The SDK follows redirects only when the protocol, host, and port stay the same.
ConnectTimeouttime.Duration10 * time.SecondTime to open the connection or wait for response headers.
ReadTimeouttime.Duration30 * time.SecondTime to wait while reading the response body.

Create a client with NewClient. Config values are validated when the client is created. Request values are validated before each request is sent.


Available Methods

MethodReturnsNotes
LookupIPGeolocation(ctx, request)*APIResponse[*IPGeolocationResponse]Single lookup. Typed JSON response.
LookupIPGeolocationRaw(ctx, request)*APIResponse[string]Single lookup. Raw JSON or XML string.
BulkLookupIPGeolocation(ctx, request)*APIResponse[[]BulkLookupResult]Bulk lookup. Typed JSON response.
BulkLookupIPGeolocationRaw(ctx, request)*APIResponse[string]Bulk lookup. Raw JSON or XML string.
LookupIPGeolocationDetailed(ctx, request)*APIResponse[*DetailedIPGeolocationResponse]Single lookup with extra CDN, proxy, bot, and corporate gateway fields.
BulkLookupIPGeolocationDetailed(ctx, request)*APIResponse[[]DetailedBulkLookupResult]Bulk lookup with the same extra fields.
Close()voidCloses idle HTTP connections and marks the client closed.

Request Options

FieldApplies ToNotes
IPSingle lookupIPv4, IPv6, or domain. Leave it empty for caller IP lookup.
IPsBulk lookupCollection of 1 to 50,000 IPs or domains.
LangSingle and bulkOne of en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt, ar (Arabic).
IncludeSingle and bulkCollection of module names such as security, abuse, user_agent, hostname, liveHostname, hostnameFallbackLive, geo_accuracy, dma_code, or *.
FieldsSingle and bulkCollection of field paths to keep, for example location.country_name or security.threat_score.
ExcludesSingle and bulkCollection of field paths to remove from the response.
UserAgentSingle and bulkOverrides the outbound User-Agent header.
HeadersSingle and bulkExtra request headers.
OutputSingle and bulkResponseFormatJSON or ResponseFormatXML. Typed methods require JSON.

Examples

The examples below assume you already have a configured client in scope:

apiKey := os.Getenv("IPGEO_API_KEY")

client, err := ipgeolocation.NewClient(&ipgeolocation.Config{
	APIKey: apiKey,
})
if err != nil {
	panic(err)
}
defer client.Close()

1. Caller IP

Leave IP empty to look up the public IP of the machine making the request.

response, err := client.LookupIPGeolocation(context.Background(), nil)
if err != nil {
	panic(err)
}

if response.Data.IP != nil {
	fmt.Println(*response.Data.IP)
}

2. Domain Lookup

Domain lookup is a paid-plan feature.

response, err := client.LookupIPGeolocation(context.Background(), &ipgeolocation.LookupRequest{
	IP: "ipgeolocation.io",
})
if err != nil {
	panic(err)
}

if response.Data.Domain != nil {
	fmt.Println(*response.Data.Domain) // ipgeolocation.io
}

3. Security and Abuse

response, err := client.LookupIPGeolocation(context.Background(), &ipgeolocation.LookupRequest{
	IP:      "9.9.9.9",
	Include: []string{"security", "abuse"},
})
if err != nil {
	panic(err)
}

if response.Data.Security != nil && response.Data.Security.ThreatScore != nil {
	fmt.Println(*response.Data.Security.ThreatScore)
}

if response.Data.Abuse != nil && len(response.Data.Abuse.Emails) > 0 {
	fmt.Println(response.Data.Abuse.Emails[0])
}

4. User-Agent Parsing

To parse a visitor user-agent string, pass Include: []string{"user_agent"} and send the visitor string in the request User-Agent header.

visitorUA := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9"

response, err := client.LookupIPGeolocation(context.Background(), &ipgeolocation.LookupRequest{
	IP:      "115.240.90.163",
	Include: []string{"user_agent"},
	Headers: map[string]string{
		"User-Agent": visitorUA,
	},
})
if err != nil {
	panic(err)
}

if response.Data.UserAgent != nil && response.Data.UserAgent.Name != nil {
	fmt.Println(*response.Data.UserAgent.Name)
}

5. Filtered Response

response, err := client.LookupIPGeolocation(context.Background(), &ipgeolocation.LookupRequest{
	IP:       "8.8.8.8",
	Include:  []string{"security"},
	Fields:   []string{"location.country_name", "security.threat_score", "security.is_vpn"},
	Excludes: []string{"currency"},
})
if err != nil {
	panic(err)
}

if response.Data.Location != nil && response.Data.Location.CountryName != nil {
	fmt.Println(*response.Data.Location.CountryName)
}

if response.Data.Security != nil && response.Data.Security.IsVPN != nil {
	fmt.Println(*response.Data.Security.IsVPN)
}

fmt.Println(response.Data.Currency == nil)

6. Raw XML

response, err := client.LookupIPGeolocationRaw(context.Background(), &ipgeolocation.LookupRequest{
	IP:     "8.8.8.8",
	Output: ipgeolocation.ResponseFormatXML,
})
if err != nil {
	panic(err)
}

fmt.Println(response.Data)

7. Bulk Lookup

A typed bulk lookup returns one result for each input, in the same order. If the API sends too few or too many results, the SDK returns *SerializationError. Raw lookups return the response as received.

response, err := client.BulkLookupIPGeolocation(context.Background(), &ipgeolocation.BulkLookupRequest{
	IPs: []string{"8.8.8.8", "1.1.1.1"},
})
if err != nil {
	panic(err)
}

for _, result := range response.Data {
	if result.IsSuccess() && result.Data != nil && result.Data.IP != nil {
		fmt.Println(*result.Data.IP)
		continue
	}

	if result.Error != nil {
		fmt.Println(result.Error.Message)
	}
}

8. Raw Bulk JSON

response, err := client.BulkLookupIPGeolocationRaw(context.Background(), &ipgeolocation.BulkLookupRequest{
	IPs: []string{"8.8.8.8", "1.1.1.1"},
})
if err != nil {
	panic(err)
}

fmt.Println(response.Data)

Response Metadata

Every method returns APIResponse[T], where:

  • Data contains the typed object or raw response string
  • Metadata contains response details such as:
    • CreditsCharged
    • SuccessfulRecords
    • StatusCode
    • DurationMS
    • RawHeaders

Example:

fmt.Println(response.Metadata.StatusCode)
fmt.Println(response.Metadata.DurationMS)
fmt.Println(response.Metadata.FirstHeaderValue("content-type"))

Errors

The SDK hides your API key when you print a client or its settings with fmt, and in request errors and typed bulk error messages. If an API error is too large to read or the connection closes early, you still get the HTTP status. If a custom network error could contain your key, the SDK may return its message without the original error type.

Error TypeWhen It Happens
*ValidationErrorInvalid config, invalid request values, or typed XML request
*RequestTimeoutErrorConnect timeout or read timeout
*TransportErrorNetwork or transport failure
*SerializationErrorRequest or response serialization failure
*APIErrorAPI returned a non-2xx response

*APIError has status-specific types:

  • *BadRequestError
  • *UnauthorizedError
  • *ForbiddenError
  • *NotFoundError
  • *MethodNotAllowedError
  • *ContentTooLargeError
  • *UnsupportedMediaTypeError
  • *LockedError
  • *TooManyRequestsError
  • *CustomStatus499Error
  • *InternalServerError

Example:

var validationErr *ipgeolocation.ValidationError

_, err := client.LookupIPGeolocation(context.Background(), &ipgeolocation.LookupRequest{
	Output: ipgeolocation.ResponseFormatXML,
})
if err != nil {
	if errors.As(err, &validationErr) {
		fmt.Println(validationErr.Message)
		return
	}

	fmt.Println(err)
}

Troubleshooting

  • Set APIKey before making a lookup.
  • Typed methods only support JSON. Use the raw methods for XML.
  • If you need security, abuse, user-agent, or hostname data, include those modules explicitly.
  • Fields and Excludes filter the response. They do not unlock paid data.
  • Response fields are pointers so omitted fields stay omitted.

Frequently Asked Questions

No. Typed methods only support JSON. Use LookupIPGeolocationRaw or BulkLookupIPGeolocationRaw for XML.
Pointers let the SDK preserve omitted fields instead of inventing zero values for data the API did not send.
No. Domain lookup is a paid-plan feature.

Links

Subscribe to Our Newsletter

Get the latest in geolocation tech, straight to your inbox.