IPIDB

IP geolocation in Go

A small Go client for IP geolocation with net/http and encoding/json: typed response structs, timeouts, error codes and a lookup of many addresses in one batch.

This guide writes a small IP geolocation client in Go with only the standard library: net/http for the request, encoding/json for typed responses, a context with a timeout, and a batch call for many addresses. It works with Go 1.20 and newer.

Setup

Shell
mkdir geo && cd geo
go mod init example.com/geo
export IPIDB_KEY=your_api_key

The key comes from the IPIDB dashboard. The free plan covers 1,000 lookups a day.

Response types

Declare only the fields you use; encoding/json ignores the rest. Pointers are used where the API can return null, for example a district that is not known.

ipidb.go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"
)

type Location struct {
	Continent   string  `json:"continent"`
	Country     string  `json:"country"`
	CountryCode string  `json:"country_code"`
	Region      string  `json:"region"`
	City        string  `json:"city"`
	District    *string `json:"district"`
	PostalCode  string  `json:"postal_code"`
	Latitude    float64 `json:"latitude"`
	Longitude   float64 `json:"longitude"`
	AccuracyKm  int     `json:"accuracy_radius_km"`
	IsEU        bool    `json:"is_eu"`
}

type Network struct {
	ASN            int    `json:"asn"`
	ISP            string `json:"isp"`
	Organization   string `json:"organization"`
	Domain         string `json:"domain"`
	ConnectionType string `json:"connection_type"`
}

type APIError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

type IPResponse struct {
	Success  bool     `json:"success"`
	IP       string   `json:"ip"`
	Version  int      `json:"version"`
	Location Location `json:"location"`
	Timezone struct {
		ID string `json:"id"`
	} `json:"timezone"`
	Network Network   `json:"network"`
	Error   *APIError `json:"error"`
}

const api = "https://api.ipidb.com/v1"

var client = &http.Client{Timeout: 5 * time.Second}

func do(ctx context.Context, req *http.Request, out any) error {
	req = req.WithContext(ctx)
	req.Header.Set("X-API-Key", os.Getenv("IPIDB_KEY"))
	res, err := client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	return json.NewDecoder(res.Body).Decode(out)
}

// Lookup returns the location and network of one address.
func Lookup(ctx context.Context, ip string) (*IPResponse, error) {
	req, _ := http.NewRequest(http.MethodGet, api+"/ip/"+url.PathEscape(ip), nil)
	var r IPResponse
	if err := do(ctx, req, &r); err != nil {
		return nil, err
	}
	if !r.Success {
		return nil, fmt.Errorf("ipidb: %s", r.Error.Code)
	}
	return &r, nil
}

// Batch looks up many addresses in one request (paid plans).
func Batch(ctx context.Context, ips []string) ([]IPResponse, error) {
	body, _ := json.Marshal(map[string][]string{"ips": ips})
	req, _ := http.NewRequest(http.MethodPost, api+"/ip/batch", strings.NewReader(string(body)))
	req.Header.Set("Content-Type", "application/json")
	var r struct {
		Success bool         `json:"success"`
		Results []IPResponse `json:"results"`
		Error   *APIError    `json:"error"`
	}
	if err := do(ctx, req, &r); err != nil {
		return nil, err
	}
	if !r.Success {
		return nil, fmt.Errorf("ipidb: %s", r.Error.Code)
	}
	return r.Results, nil
}

Using it

main.go
package main

import (
	"context"
	"fmt"
	"log"
	"time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	r, err := Lookup(ctx, "8.8.8.8")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s, %s, %s (AS%d %s)\n",
		r.Location.City, r.Location.Region, r.Location.CountryCode,
		r.Network.ASN, r.Network.ISP)
	fmt.Println("time zone:", r.Timezone.ID)
}

Run go run . in the folder. For 8.8.8.8 the output is Mountain View, California, US (AS15169 Google) and the time zone America/Los_Angeles.

Batch lookups

With a paid key, Batch sends up to 100 addresses on Starter and Pro and up to 1,000 on Business in one request. Results come back in the order you sent them; an invalid address has Success set to false and its own Error, while the rest of the batch is answered normally.

Batch
results, err := Batch(ctx, []string{"8.8.8.8", "1.1.1.1", "2a00:1450:4001::1"})
if err != nil {
	log.Fatal(err)
}
for _, r := range results {
	if r.Success {
		fmt.Println(r.IP, r.Location.CountryCode)
	} else {
		fmt.Println(r.IP, "error:", r.Error.Code)
	}
}

Practical notes

  • Reuse one http.Client; it keeps connections open between requests.
  • Cache answers for a few hours. A sync.Map works for a single process; use Redis when several instances share the work.
  • On HTTP 429 with rate_limited, wait for the Retry-After seconds and send the request again. quota_exceeded means the quota for the day or month is used.
  • The documentation lists every field; paid plans add security, abuse and country_info objects that you can add to IPResponse the same way.

Related