├── .gitignore ├── scripts ├── lint.sh ├── fmt.sh └── ctags.sh ├── go.mod ├── example ├── get-org │ └── main.go ├── get-city │ └── main.go ├── my-ip-info │ └── main.go ├── get-bogon │ └── main.go ├── get-location │ └── main.go ├── get-postal │ └── main.go ├── get-region │ └── main.go ├── get-anycast │ └── main.go ├── get-country │ └── main.go ├── get-hostname │ └── main.go ├── get-timezone │ └── main.go ├── get-country-name │ └── main.go ├── ipv6 │ └── main.go ├── asn │ └── main.go ├── quickstart.go ├── cache │ ├── in-memory │ │ └── main.go │ └── main.go ├── ip-details │ └── main.go ├── ip-details-lite │ └── main.go ├── batch-asn │ └── main.go ├── batch-core-str │ └── main.go ├── batch-core-netip │ └── main.go ├── batch-generic │ └── main.go ├── ip-summary │ └── main.go ├── lookup-core │ └── main.go └── lookup-plus │ └── main.go ├── go.sum ├── ipinfo ├── cache.go ├── doc.go ├── ipinfo.go ├── cache │ ├── interface.go │ └── in_memory.go ├── map.go ├── summary.go ├── asn.go ├── bogon.go ├── lite.go ├── core_new.go ├── client.go ├── plus.go ├── batch.go ├── core.go └── countries.go ├── .github └── workflows │ └── ci.yaml ├── CHANGELOG.md ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .vim/ 2 | -------------------------------------------------------------------------------- /scripts/lint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Lint all files in the project. 4 | 5 | golint ./... 6 | -------------------------------------------------------------------------------- /scripts/fmt.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DIR=`dirname $0` 4 | ROOT=$DIR/.. 5 | 6 | # Format code in project. 7 | 8 | gofmt -w \ 9 | $ROOT/example \ 10 | $ROOT/ipinfo 11 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/ipinfo/go/v2 2 | 3 | go 1.18 4 | 5 | require ( 6 | github.com/patrickmn/go-cache v2.1.0+incompatible 7 | golang.org/x/sync v0.0.0-20220513210516-0976fa681c29 8 | ) 9 | -------------------------------------------------------------------------------- /example/get-org/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/ipinfo/go/v2/ipinfo" 8 | ) 9 | 10 | func main() { 11 | org, err := ipinfo.GetIPOrg(nil) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | fmt.Printf("%v\n", org) 16 | } 17 | -------------------------------------------------------------------------------- /example/get-city/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/ipinfo/go/v2/ipinfo" 8 | ) 9 | 10 | func main() { 11 | city, err := ipinfo.GetIPCity(nil) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | fmt.Printf("%v\n", city) 16 | } 17 | -------------------------------------------------------------------------------- /example/my-ip-info/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/ipinfo/go/v2/ipinfo" 8 | ) 9 | 10 | func main() { 11 | core, err := ipinfo.GetIPInfo(nil) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | fmt.Printf("%v\n", core) 16 | } 17 | -------------------------------------------------------------------------------- /example/get-bogon/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/ipinfo/go/v2/ipinfo" 8 | ) 9 | 10 | func main() { 11 | bogon, err := ipinfo.GetIPBogon(nil) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | fmt.Printf("%v\n", bogon) 16 | } 17 | -------------------------------------------------------------------------------- /example/get-location/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/ipinfo/go/v2/ipinfo" 8 | ) 9 | 10 | func main() { 11 | loc, err := ipinfo.GetIPLocation(nil) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | fmt.Printf("%v\n", loc) 16 | } 17 | -------------------------------------------------------------------------------- /example/get-postal/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/ipinfo/go/v2/ipinfo" 8 | ) 9 | 10 | func main() { 11 | postal, err := ipinfo.GetIPPostal(nil) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | fmt.Printf("%v\n", postal) 16 | } 17 | -------------------------------------------------------------------------------- /example/get-region/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/ipinfo/go/v2/ipinfo" 8 | ) 9 | 10 | func main() { 11 | region, err := ipinfo.GetIPRegion(nil) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | fmt.Printf("%v\n", region) 16 | } 17 | -------------------------------------------------------------------------------- /example/get-anycast/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/ipinfo/go/v2/ipinfo" 8 | ) 9 | 10 | func main() { 11 | anycast, err := ipinfo.GetIPAnycast(nil) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | fmt.Printf("%v\n", anycast) 16 | } 17 | -------------------------------------------------------------------------------- /example/get-country/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/ipinfo/go/v2/ipinfo" 8 | ) 9 | 10 | func main() { 11 | country, err := ipinfo.GetIPCountry(nil) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | fmt.Printf("%v\n", country) 16 | } 17 | -------------------------------------------------------------------------------- /example/get-hostname/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/ipinfo/go/v2/ipinfo" 8 | ) 9 | 10 | func main() { 11 | hostname, err := ipinfo.GetIPHostname(nil) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | fmt.Printf("%v\n", hostname) 16 | } 17 | -------------------------------------------------------------------------------- /example/get-timezone/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/ipinfo/go/v2/ipinfo" 8 | ) 9 | 10 | func main() { 11 | timezone, err := ipinfo.GetIPTimezone(nil) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | fmt.Printf("%v\n", timezone) 16 | } 17 | -------------------------------------------------------------------------------- /example/get-country-name/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/ipinfo/go/v2/ipinfo" 8 | ) 9 | 10 | func main() { 11 | countryName, err := ipinfo.GetIPCountryName(nil) 12 | if err != nil { 13 | log.Fatal(err) 14 | } 15 | fmt.Printf("%v\n", countryName) 16 | } 17 | -------------------------------------------------------------------------------- /example/ipv6/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | 8 | "github.com/ipinfo/go/v2/ipinfo" 9 | ) 10 | 11 | func main() { 12 | core, err := ipinfo.GetIPInfo(net.ParseIP("2a03:2880:f10a:83:face:b00c:0:25de")) 13 | if err != nil { 14 | log.Fatal(err) 15 | } 16 | fmt.Printf("%v\n", core) 17 | } 18 | -------------------------------------------------------------------------------- /scripts/ctags.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Regenerate ctags. 4 | 5 | ctags \ 6 | --recurse=yes \ 7 | --exclude=node_modules \ 8 | --exclude=dist \ 9 | --exclude=build \ 10 | --exclude=target \ 11 | -f .vim/tags \ 12 | --tag-relative=never \ 13 | --totals=yes \ 14 | ./ipinfo \ 15 | ./example 16 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= 2 | github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= 3 | golang.org/x/sync v0.0.0-20220513210516-0976fa681c29 h1:w8s32wxx3sY+OjLlv9qltkLU5yvJzxjjgiHWLjdIcw4= 4 | golang.org/x/sync v0.0.0-20220513210516-0976fa681c29/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 5 | -------------------------------------------------------------------------------- /example/asn/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | 8 | "github.com/ipinfo/go/v2/ipinfo" 9 | ) 10 | 11 | func main() { 12 | // Get access token by signing up a free account at 13 | // https://ipinfo.io/signup. 14 | // Provide token as an environment variable `TOKEN`, 15 | // e.g. TOKEN="XXXXXXXXXXXXXX" go run main.go 16 | client := ipinfo.NewClient(nil, nil, os.Getenv("TOKEN")) 17 | asnDetails, err := client.GetASNDetails("AS7922") 18 | if err != nil { 19 | log.Fatal(err) 20 | } 21 | fmt.Printf("%v\n", asnDetails) 22 | } 23 | -------------------------------------------------------------------------------- /ipinfo/cache.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/ipinfo/go/v2/ipinfo/cache" 7 | ) 8 | 9 | const cacheKeyVsn = "2" 10 | 11 | // Cache represents the internal cache used by the IPinfo client. 12 | type Cache struct { 13 | cache.Interface 14 | } 15 | 16 | // NewCache creates a new cache given a specific engine. 17 | func NewCache(engine cache.Interface) *Cache { 18 | return &Cache{Interface: engine} 19 | } 20 | 21 | // return a versioned cache key. 22 | func cacheKey(k string) string { 23 | return fmt.Sprintf("%s:%s", k, cacheKeyVsn) 24 | } 25 | -------------------------------------------------------------------------------- /example/quickstart.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | "os" 8 | 9 | "github.com/ipinfo/go/v2/ipinfo" 10 | ) 11 | 12 | func main() { 13 | // Get access token by signing up a free account at 14 | // https://ipinfo.io/signup. 15 | // Provide token as an environment variable `TOKEN`, 16 | // e.g. TOKEN="XXXXXXXXXXXXXX" go run main.go 17 | client := ipinfo.NewClient(nil, nil, os.Getenv("TOKEN")) 18 | core, err := client.GetIPInfo(net.ParseIP("8.8.8.8")) 19 | if err != nil { 20 | log.Fatal(err) 21 | } 22 | fmt.Printf("%v\n", core) 23 | } 24 | -------------------------------------------------------------------------------- /ipinfo/doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package ipinfo provides a client for using the IPinfo API. 3 | 4 | Usage: 5 | 6 | import "github.com/ipinfo/go/v2/ipinfo" 7 | 8 | The default IPinfo client is predefined and can be used without initialization. 9 | For example: 10 | 11 | info, err := ipinfo.GetIPInfo(net.ParseIP("8.8.8.8")) 12 | 13 | # Authorization 14 | 15 | To perform authorized API calls with more data and higher limits, pass in a 16 | non-empty token to NewClient. For example: 17 | 18 | client := ipinfo.NewClient(nil, nil, "MY_TOKEN") 19 | info, err := client.GetIPInfo(net.ParseIP("8.8.8.8")) 20 | */ 21 | package ipinfo 22 | -------------------------------------------------------------------------------- /ipinfo/ipinfo.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | // DefaultClient is the package-level client available to the user. 4 | var DefaultClient *Client 5 | 6 | // Package-level Lite bundle client 7 | var DefaultLiteClient *LiteClient 8 | 9 | // Package-level Core bundle client 10 | var DefaultCoreClient *CoreClient 11 | 12 | // Package-level Plus bundle client 13 | var DefaultPlusClient *PlusClient 14 | 15 | func init() { 16 | // Create global clients for legacy, Lite, Core APIs 17 | DefaultClient = NewClient(nil, nil, "") 18 | DefaultLiteClient = NewLiteClient(nil, nil, "") 19 | DefaultCoreClient = NewCoreClient(nil, nil, "") 20 | DefaultPlusClient = NewPlusClient(nil, nil, "") 21 | } 22 | -------------------------------------------------------------------------------- /example/cache/in-memory/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | "os" 8 | "time" 9 | 10 | "github.com/ipinfo/go/v2/ipinfo" 11 | "github.com/ipinfo/go/v2/ipinfo/cache" 12 | ) 13 | 14 | func main() { 15 | ipinfo.SetCache( 16 | ipinfo.NewCache( 17 | cache.NewInMemory().WithExpiration(5 * time.Minute), 18 | ), 19 | ) 20 | ipinfo.SetToken(os.Getenv("TOKEN")) 21 | ip := net.ParseIP("8.8.8.8") 22 | 23 | for i := 0; i < 2; i++ { 24 | fmt.Println([]string{"Actual requests", "From cache"}[i]) 25 | if v, err := ipinfo.GetIPInfo(ip); err != nil { 26 | log.Println(err) 27 | } else { 28 | fmt.Printf("IP: %v\n", v) 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ipinfo/cache/interface.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | import "errors" 4 | 5 | var ( 6 | // ErrNotFound means that the key was not found. 7 | ErrNotFound = errors.New("key not found") 8 | ) 9 | 10 | // Interface is the cache interface that all cache implementations must adhere 11 | // to at the minimum to be usable in the IPinfo client. 12 | // 13 | // Note that all implementations must be concurrency-safe. 14 | type Interface interface { 15 | // Get a value from the cache given a key. 16 | // 17 | // This must be concurrency-safe. 18 | Get(key string) (interface{}, error) 19 | 20 | // Set a key to value mapping in the cache. 21 | // 22 | // This must be concurrency-safe. 23 | Set(key string, value interface{}) error 24 | } 25 | -------------------------------------------------------------------------------- /example/ip-details/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | "os" 8 | 9 | "github.com/ipinfo/go/v2/ipinfo" 10 | ) 11 | 12 | func main() { 13 | var c *ipinfo.Client 14 | 15 | if token := os.Getenv("TOKEN"); token != "" { 16 | c = ipinfo.NewClient(nil, nil, token) 17 | } else { 18 | c = ipinfo.DefaultClient 19 | } 20 | 21 | /* default to user IP */ 22 | if len(os.Args) == 1 { 23 | core, err := c.GetIPInfo(nil) 24 | if err != nil { 25 | log.Println(err) 26 | } 27 | fmt.Printf("%v\n", core) 28 | return 29 | } 30 | 31 | for _, s := range os.Args[1:] { 32 | ip := net.ParseIP(s) 33 | if ip == nil { 34 | continue 35 | } 36 | core, err := c.GetIPInfo(ip) 37 | if err != nil { 38 | log.Println(err) 39 | } 40 | fmt.Printf("%v\n", core) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /example/ip-details-lite/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | "os" 8 | 9 | "github.com/ipinfo/go/v2/ipinfo" 10 | ) 11 | 12 | func main() { 13 | var c *ipinfo.LiteClient 14 | 15 | if token := os.Getenv("TOKEN"); token != "" { 16 | c = ipinfo.NewLiteClient(nil, nil, token) 17 | } else { 18 | c = ipinfo.DefaultLiteClient 19 | } 20 | 21 | /* default to user IP */ 22 | if len(os.Args) == 1 { 23 | info, err := c.GetIPInfo(nil) 24 | if err != nil { 25 | log.Println(err) 26 | } 27 | fmt.Printf("%v\n", info) 28 | return 29 | } 30 | 31 | for _, s := range os.Args[1:] { 32 | ip := net.ParseIP(s) 33 | if ip == nil { 34 | continue 35 | } 36 | info, err := c.GetIPInfo(ip) 37 | if err != nil { 38 | log.Println(err) 39 | } 40 | fmt.Printf("%v\n", info) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /example/batch-asn/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "time" 8 | 9 | "github.com/ipinfo/go/v2/ipinfo" 10 | "github.com/ipinfo/go/v2/ipinfo/cache" 11 | ) 12 | 13 | func main() { 14 | client := ipinfo.NewClient( 15 | nil, 16 | ipinfo.NewCache(cache.NewInMemory().WithExpiration(5*time.Minute)), 17 | os.Getenv("TOKEN"), 18 | ) 19 | for i := 0; i < 3; i++ { 20 | fmt.Printf("doing lookup #%v\n", i) 21 | batchResult, err := client.GetASNDetailsBatch( 22 | []string{ 23 | "AS321", 24 | "AS999", 25 | }, 26 | ipinfo.BatchReqOpts{ 27 | TimeoutPerBatch: 0, 28 | TimeoutTotal: 5, 29 | }, 30 | ) 31 | if err != nil { 32 | log.Fatal(err) 33 | } 34 | for k, v := range batchResult { 35 | fmt.Printf("k=%v v=%v\n", k, v) 36 | } 37 | fmt.Println() 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /example/batch-core-str/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "time" 8 | 9 | "github.com/ipinfo/go/v2/ipinfo" 10 | "github.com/ipinfo/go/v2/ipinfo/cache" 11 | ) 12 | 13 | func main() { 14 | client := ipinfo.NewClient( 15 | nil, 16 | ipinfo.NewCache(cache.NewInMemory().WithExpiration(5*time.Minute)), 17 | os.Getenv("TOKEN"), 18 | ) 19 | for i := 0; i < 3; i++ { 20 | fmt.Printf("doing lookup #%v\n", i) 21 | batchResult, err := client.GetIPStrInfoBatch( 22 | []string{ 23 | "1.1.1.1", 24 | "8.8.8.8", 25 | }, 26 | ipinfo.BatchReqOpts{ 27 | TimeoutPerBatch: 0, 28 | TimeoutTotal: 5, 29 | }, 30 | ) 31 | if err != nil { 32 | log.Fatal(err) 33 | } 34 | for k, v := range batchResult { 35 | fmt.Printf("k=%v v=%v\n", k, v) 36 | } 37 | fmt.Println() 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /example/batch-core-netip/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | "os" 8 | "time" 9 | 10 | "github.com/ipinfo/go/v2/ipinfo" 11 | "github.com/ipinfo/go/v2/ipinfo/cache" 12 | ) 13 | 14 | func main() { 15 | client := ipinfo.NewClient( 16 | nil, 17 | ipinfo.NewCache(cache.NewInMemory().WithExpiration(5*time.Minute)), 18 | os.Getenv("TOKEN"), 19 | ) 20 | for i := 0; i < 3; i++ { 21 | fmt.Printf("doing lookup #%v\n", i) 22 | batchResult, err := client.GetIPInfoBatch( 23 | []net.IP{ 24 | net.ParseIP("1.1.1.1"), 25 | net.ParseIP("8.8.8.8"), 26 | }, 27 | ipinfo.BatchReqOpts{ 28 | TimeoutPerBatch: 0, 29 | TimeoutTotal: 5, 30 | }, 31 | ) 32 | if err != nil { 33 | log.Fatal(err) 34 | } 35 | for k, v := range batchResult { 36 | fmt.Printf("k=%v v=%v\n", k, v) 37 | } 38 | fmt.Println() 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /example/batch-generic/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "time" 8 | 9 | "github.com/ipinfo/go/v2/ipinfo" 10 | "github.com/ipinfo/go/v2/ipinfo/cache" 11 | ) 12 | 13 | func main() { 14 | client := ipinfo.NewClient( 15 | nil, 16 | ipinfo.NewCache(cache.NewInMemory().WithExpiration(5*time.Minute)), 17 | os.Getenv("TOKEN"), 18 | ) 19 | for i := 0; i < 3; i++ { 20 | fmt.Printf("doing lookup #%v\n", i) 21 | batchResult, err := client.GetBatch( 22 | []string{ 23 | "1.1.1.1", 24 | "1.1.1.1/country", 25 | "8.8.8.8", 26 | "8.8.8.8/country", 27 | "AS321", 28 | }, 29 | ipinfo.BatchReqOpts{ 30 | BatchSize: 2, 31 | TimeoutPerBatch: 0, 32 | TimeoutTotal: 5, 33 | }, 34 | ) 35 | if err != nil { 36 | log.Fatal(err) 37 | } 38 | for k, v := range batchResult { 39 | fmt.Printf("k=%v v=%v\n", k, v) 40 | } 41 | fmt.Println() 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | 3 | on: 4 | pull_request: 5 | branches: [master] 6 | push: 7 | branches: [master] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | go: ["1.18", "1.19", "1.20", "1.21", "1.22", "1.23", "1.24"] 15 | 16 | steps: 17 | - uses: actions/checkout@v4 18 | 19 | - name: Set up Go ${{ matrix.go }} 20 | uses: actions/setup-go@v5 21 | with: 22 | go-version: ${{ matrix.go }} 23 | 24 | - name: Build 25 | run: go build -v ./... 26 | 27 | - name: gofmt 28 | run: | 29 | unformatted_files=$(gofmt -l .) 30 | if [ -n "$unformatted_files" ]; then 31 | echo "The following files are not Go formatted:" 32 | echo "$unformatted_files" 33 | echo "Please run 'gofmt -w .' to fix them." 34 | exit 1 35 | fi 36 | echo "All Go files are well formatted." 37 | -------------------------------------------------------------------------------- /example/ip-summary/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | "os" 8 | 9 | "github.com/ipinfo/go/v2/ipinfo" 10 | ) 11 | 12 | func main() { 13 | client := ipinfo.NewClient(nil, nil, os.Getenv("TOKEN")) 14 | result, err := client.GetIPSummary( 15 | []net.IP{ 16 | net.ParseIP("3.3.3.0"), 17 | net.ParseIP("3.3.3.1"), 18 | net.ParseIP("3.3.3.2"), 19 | net.ParseIP("3.3.3.3"), 20 | net.ParseIP("4.4.4.0"), 21 | net.ParseIP("4.4.4.1"), 22 | net.ParseIP("4.4.4.2"), 23 | net.ParseIP("4.4.4.3"), 24 | net.ParseIP("8.8.8.0"), 25 | net.ParseIP("8.8.8.1"), 26 | net.ParseIP("8.8.8.2"), 27 | net.ParseIP("8.8.8.3"), 28 | net.ParseIP("1.1.1.0"), 29 | net.ParseIP("1.1.1.1"), 30 | net.ParseIP("1.1.1.2"), 31 | net.ParseIP("1.1.1.3"), 32 | net.ParseIP("2.2.2.0"), 33 | net.ParseIP("2.2.2.1"), 34 | net.ParseIP("2.2.2.2"), 35 | net.ParseIP("2.2.2.3"), 36 | }, 37 | ) 38 | if err != nil { 39 | log.Fatal(err) 40 | } 41 | fmt.Printf("result=%v\n", result) 42 | } 43 | -------------------------------------------------------------------------------- /ipinfo/map.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "net" 8 | ) 9 | 10 | // IPMap is the full JSON response from the IP Map API. 11 | type IPMap struct { 12 | Status string `json:"status"` 13 | ReportURL string `json:"reportUrl"` 14 | } 15 | 16 | // GetIPMap returns an IPMap result for a group of IPs. 17 | // 18 | // `len(ips)` must not exceed 500,000. 19 | func GetIPMap(ips []net.IP) (*IPMap, error) { 20 | return DefaultClient.GetIPMap(ips) 21 | } 22 | 23 | // GetIPMap returns an IPMap result for a group of IPs. 24 | // 25 | // `len(ips)` must not exceed 500,000. 26 | func (c *Client) GetIPMap(ips []net.IP) (*IPMap, error) { 27 | if len(ips) > 500000 { 28 | return nil, errors.New("ip count must be <500,000") 29 | } 30 | 31 | jsonArrStr, err := json.Marshal(ips) 32 | if err != nil { 33 | return nil, err 34 | } 35 | jsonBuf := bytes.NewBuffer(jsonArrStr) 36 | 37 | req, err := c.newRequest(nil, "POST", "map?cli=1", jsonBuf) 38 | if err != nil { 39 | return nil, err 40 | } 41 | req.Header.Set("Content-Type", "application/json") 42 | 43 | result := new(IPMap) 44 | if _, err := c.do(req, result); err != nil { 45 | return nil, err 46 | } 47 | 48 | return result, nil 49 | } 50 | -------------------------------------------------------------------------------- /example/lookup-core/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | "os" 8 | 9 | "github.com/ipinfo/go/v2/ipinfo" 10 | ) 11 | 12 | func main() { 13 | client := ipinfo.NewCoreClient(nil, nil, os.Getenv("IPINFO_TOKEN")) 14 | 15 | ip := net.ParseIP("8.8.8.8") 16 | info, err := client.GetIPInfo(ip) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | 21 | fmt.Printf("IP: %s\n", info.IP) 22 | if info.Geo != nil { 23 | fmt.Printf("City: %s\n", info.Geo.City) 24 | fmt.Printf("Region: %s\n", info.Geo.Region) 25 | fmt.Printf("Country: %s (%s)\n", info.Geo.Country, info.Geo.CountryCode) 26 | fmt.Printf("Location: %f, %f\n", info.Geo.Latitude, info.Geo.Longitude) 27 | fmt.Printf("Timezone: %s\n", info.Geo.Timezone) 28 | fmt.Printf("Postal Code: %s\n", info.Geo.PostalCode) 29 | } 30 | if info.AS != nil { 31 | fmt.Printf("ASN: %s\n", info.AS.ASN) 32 | fmt.Printf("AS Name: %s\n", info.AS.Name) 33 | fmt.Printf("AS Domain: %s\n", info.AS.Domain) 34 | fmt.Printf("AS Type: %s\n", info.AS.Type) 35 | } 36 | fmt.Printf("Anonymous: %v\n", info.IsAnonymous) 37 | fmt.Printf("Anycast: %v\n", info.IsAnycast) 38 | fmt.Printf("Hosting: %v\n", info.IsHosting) 39 | fmt.Printf("Mobile: %v\n", info.IsMobile) 40 | fmt.Printf("Satellite: %v\n", info.IsSatellite) 41 | } 42 | -------------------------------------------------------------------------------- /ipinfo/cache/in_memory.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/patrickmn/go-cache" 7 | ) 8 | 9 | const defaultExpiration = 24 * time.Hour 10 | 11 | // InMemory is an implementation of the cache interface which stores values 12 | // in-memory. 13 | type InMemory struct { 14 | cache *cache.Cache 15 | expiration time.Duration 16 | } 17 | 18 | // NewInMemory creates a new InMemory instance with default values. 19 | func NewInMemory() *InMemory { 20 | return &InMemory{ 21 | cache: cache.New(-1, defaultExpiration), 22 | expiration: defaultExpiration, 23 | } 24 | } 25 | 26 | // WithExpiration updates the expiration value of `c`. 27 | func (c *InMemory) WithExpiration(d time.Duration) *InMemory { 28 | c.expiration = d 29 | return c 30 | } 31 | 32 | // Get retrieves a value from the InMemory cache implementation. 33 | func (c *InMemory) Get(key string) (interface{}, error) { 34 | v, found := c.cache.Get(key) 35 | if !found { 36 | return nil, ErrNotFound 37 | } 38 | return v, nil 39 | } 40 | 41 | // Set sets a value for a key in the InMemory cache implementation. 42 | func (c *InMemory) Set(key string, value interface{}) error { 43 | c.cache.Set(key, value, c.expiration) 44 | return nil 45 | } 46 | 47 | // Check if InMemory implements cache.Interface 48 | var _ Interface = (*InMemory)(nil) 49 | -------------------------------------------------------------------------------- /example/cache/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | "os" 8 | 9 | "github.com/ipinfo/go/v2/ipinfo" 10 | "github.com/ipinfo/go/v2/ipinfo/cache" 11 | ) 12 | 13 | type dummyCacheEngine struct { 14 | cache map[string]interface{} 15 | } 16 | 17 | func newDummyCacheEngine() *dummyCacheEngine { 18 | return &dummyCacheEngine{ 19 | cache: make(map[string]interface{}), 20 | } 21 | } 22 | 23 | func (c *dummyCacheEngine) Get(key string) (interface{}, error) { 24 | log.Printf("[CACHE]: Trying to get value for key %q", key) 25 | if v, ok := c.cache[key]; ok { 26 | log.Printf("[CACHE]: Got value for key %q=%q", key, v) 27 | return v, nil 28 | } 29 | log.Printf("[CACHE]: Key %q not found", key) 30 | return nil, cache.ErrNotFound 31 | } 32 | 33 | func (c *dummyCacheEngine) Set(key string, value interface{}) error { 34 | log.Printf("[CACHE]: Setting value for key %q=%q", key, value) 35 | c.cache[key] = value 36 | return nil 37 | } 38 | 39 | var dummyCache = ipinfo.NewCache(newDummyCacheEngine()) 40 | 41 | func main() { 42 | ipinfo.SetCache(dummyCache) 43 | ipinfo.SetToken(os.Getenv("TOKEN")) 44 | ip := net.ParseIP("8.8.8.8") 45 | 46 | for i := 0; i < 2; i++ { 47 | fmt.Println([]string{"Actual requests", "From cache"}[i]) 48 | if v, err := ipinfo.GetIPInfo(ip); err != nil { 49 | log.Println(err) 50 | } else { 51 | fmt.Printf("IP: %v\n", v) 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ipinfo/summary.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "net" 7 | ) 8 | 9 | // IPSummary is the full JSON response from the IP summary API. 10 | type IPSummary struct { 11 | Total uint64 `json:"total"` 12 | Unique uint64 `json:"unique"` 13 | Countries map[string]uint64 `json:"countries"` 14 | Cities map[string]uint64 `json:"cities"` 15 | Regions map[string]uint64 `json:"regions"` 16 | ASNs map[string]uint64 `json:"asns"` 17 | Companies map[string]uint64 `json:"companies"` 18 | IPTypes map[string]uint64 `json:"ipTypes"` 19 | Routes map[string]uint64 `json:"routes"` 20 | Carriers map[string]uint64 `json:"carriers"` 21 | Mobile uint64 `json:"mobile"` 22 | Domains map[string]uint64 `json:"domains"` 23 | Privacy struct { 24 | VPN uint64 `json:"vpn"` 25 | Proxy uint64 `json:"proxy"` 26 | Hosting uint64 `json:"hosting"` 27 | Relay uint64 `json:"relay"` 28 | Tor uint64 `json:"tor"` 29 | } `json:"privacy"` 30 | PrivacyServices map[string]uint64 `json:"privacyServices"` 31 | Anycast uint64 `json:"anycast"` 32 | Bogon uint64 `json:"bogon"` 33 | } 34 | 35 | // GetIPSummary returns summarized results for a group of IPs. 36 | func GetIPSummary(ips []net.IP) (*IPSummary, error) { 37 | return DefaultClient.GetIPSummary(ips) 38 | } 39 | 40 | // GetIPSummary returns summarized results for a group of IPs. 41 | func (c *Client) GetIPSummary(ips []net.IP) (*IPSummary, error) { 42 | jsonArrStr, err := json.Marshal(ips) 43 | if err != nil { 44 | return nil, err 45 | } 46 | jsonBuf := bytes.NewBuffer(jsonArrStr) 47 | 48 | req, err := c.newRequest(nil, "POST", "summarize?cli=1", jsonBuf) 49 | if err != nil { 50 | return nil, err 51 | } 52 | req.Header.Set("Content-Type", "application/json") 53 | 54 | result := new(IPSummary) 55 | if _, err := c.do(req, result); err != nil { 56 | return nil, err 57 | } 58 | 59 | return result, nil 60 | } 61 | -------------------------------------------------------------------------------- /example/lookup-plus/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net" 7 | "os" 8 | 9 | "github.com/ipinfo/go/v2/ipinfo" 10 | ) 11 | 12 | func main() { 13 | client := ipinfo.NewPlusClient(nil, nil, os.Getenv("IPINFO_TOKEN")) 14 | 15 | ip := net.ParseIP("8.8.8.8") 16 | info, err := client.GetIPInfo(ip) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | 21 | fmt.Printf("IP: %s\n", info.IP) 22 | fmt.Printf("Hostname: %s\n", info.Hostname) 23 | if info.Geo != nil { 24 | fmt.Printf("City: %s\n", info.Geo.City) 25 | fmt.Printf("Region: %s (%s)\n", info.Geo.Region, info.Geo.RegionCode) 26 | fmt.Printf("Country: %s (%s)\n", info.Geo.Country, info.Geo.CountryCode) 27 | fmt.Printf("Continent: %s (%s)\n", info.Geo.Continent, info.Geo.ContinentCode) 28 | fmt.Printf("Location: %f, %f\n", info.Geo.Latitude, info.Geo.Longitude) 29 | fmt.Printf("Timezone: %s\n", info.Geo.Timezone) 30 | fmt.Printf("Postal Code: %s\n", info.Geo.PostalCode) 31 | } 32 | if info.AS != nil { 33 | fmt.Printf("ASN: %s\n", info.AS.ASN) 34 | fmt.Printf("AS Name: %s\n", info.AS.Name) 35 | fmt.Printf("AS Domain: %s\n", info.AS.Domain) 36 | fmt.Printf("AS Type: %s\n", info.AS.Type) 37 | } 38 | if info.Mobile != nil { 39 | fmt.Printf("Mobile - Name: %s, MCC: %s, MNC: %s\n", 40 | info.Mobile.Name, info.Mobile.MCC, info.Mobile.MNC) 41 | } 42 | if info.Anonymous != nil { 43 | fmt.Printf("Anonymous - Proxy: %v, Relay: %v, Tor: %v, VPN: %v\n", 44 | info.Anonymous.IsProxy, info.Anonymous.IsRelay, info.Anonymous.IsTor, info.Anonymous.IsVPN) 45 | } 46 | fmt.Printf("Anonymous: %v\n", info.IsAnonymous) 47 | fmt.Printf("Anycast: %v\n", info.IsAnycast) 48 | fmt.Printf("Hosting: %v\n", info.IsHosting) 49 | fmt.Printf("Mobile: %v\n", info.IsMobile) 50 | fmt.Printf("Satellite: %v\n", info.IsSatellite) 51 | if info.Abuse != nil { 52 | fmt.Printf("Abuse Contact - Email: %s, Name: %s\n", info.Abuse.Email, info.Abuse.Name) 53 | } 54 | if info.Company != nil { 55 | fmt.Printf("Company - Name: %s, Domain: %s, Type: %s\n", 56 | info.Company.Name, info.Company.Domain, info.Company.Type) 57 | } 58 | if info.Privacy != nil { 59 | fmt.Printf("Privacy - VPN: %v, Proxy: %v, Tor: %v, Relay: %v, Hosting: %v\n", 60 | info.Privacy.VPN, info.Privacy.Proxy, info.Privacy.Tor, info.Privacy.Relay, info.Privacy.Hosting) 61 | } 62 | if info.Domains != nil { 63 | fmt.Printf("Domains - Total: %d\n", info.Domains.Total) 64 | if len(info.Domains.Domains) > 0 { 65 | maxDomains := 3 66 | if len(info.Domains.Domains) < maxDomains { 67 | maxDomains = len(info.Domains.Domains) 68 | } 69 | fmt.Printf("Sample Domains: %v\n", info.Domains.Domains[:maxDomains]) 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /ipinfo/asn.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | // ASNDetails represents details for an ASN. 8 | type ASNDetails struct { 9 | ASN string `json:"asn"` 10 | Name string `json:"name"` 11 | Country string `json:"country"` 12 | CountryName string `json:"-"` 13 | Allocated string `json:"allocated"` 14 | Registry string `json:"registry"` 15 | Domain string `json:"domain"` 16 | NumIPs uint64 `json:"num_ips"` 17 | Type string `json:"type"` 18 | Prefixes []ASNDetailsPrefix `json:"prefixes"` 19 | Prefixes6 []ASNDetailsPrefix `json:"prefixes6"` 20 | Peers []string `json:"peers"` 21 | Upstreams []string `json:"upstreams"` 22 | Downstreams []string `json:"downstreams"` 23 | } 24 | 25 | // ASNDetailsPrefix represents data for prefixes managed by an ASN. 26 | type ASNDetailsPrefix struct { 27 | Netblock string `json:"netblock"` 28 | ID string `json:"id"` 29 | Name string `json:"name"` 30 | Country string `json:"country"` 31 | Size string `json:"size"` 32 | Status string `json:"status"` 33 | Domain string `json:"domain"` 34 | } 35 | 36 | // InvalidASNError is reported when the invalid ASN was specified. 37 | type InvalidASNError struct { 38 | ASN string 39 | } 40 | 41 | func (err *InvalidASNError) Error() string { 42 | return "invalid ASN: " + err.ASN 43 | } 44 | 45 | func (v *ASNDetails) setCountryName() { 46 | if v.Country != "" { 47 | v.CountryName = countriesMap[v.Country] 48 | } 49 | } 50 | 51 | // GetASNDetails returns the details for the specified ASN. 52 | func GetASNDetails(asn string) (*ASNDetails, error) { 53 | return DefaultClient.GetASNDetails(asn) 54 | } 55 | 56 | // GetASNDetails returns the details for the specified ASN. 57 | func (c *Client) GetASNDetails(asn string) (*ASNDetails, error) { 58 | if !strings.HasPrefix(asn, "AS") { 59 | return nil, &InvalidASNError{ASN: asn} 60 | } 61 | 62 | // perform cache lookup. 63 | if c.Cache != nil { 64 | if res, err := c.Cache.Get(cacheKey(asn)); err == nil { 65 | return res.(*ASNDetails), nil 66 | } 67 | } 68 | 69 | // prepare req 70 | req, err := c.newRequest(nil, "GET", asn, nil) 71 | if err != nil { 72 | return nil, err 73 | } 74 | 75 | // do req 76 | v := new(ASNDetails) 77 | if _, err := c.do(req, v); err != nil { 78 | return nil, err 79 | } 80 | 81 | // format 82 | v.setCountryName() 83 | 84 | // cache req result 85 | if c.Cache != nil { 86 | if err := c.Cache.Set(cacheKey(asn), v); err != nil { 87 | return v, err 88 | } 89 | } 90 | 91 | return v, nil 92 | } 93 | -------------------------------------------------------------------------------- /ipinfo/bogon.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | import ( 4 | "net/netip" 5 | ) 6 | 7 | func isBogon(ip netip.Addr) bool { 8 | for _, network := range bogonNetworks { 9 | if network.Contains(ip) { 10 | return true 11 | } 12 | } 13 | return false 14 | } 15 | 16 | var bogonNetworks = []netip.Prefix{ 17 | netip.MustParsePrefix("0.0.0.0/8"), 18 | netip.MustParsePrefix("10.0.0.0/8"), 19 | netip.MustParsePrefix("100.64.0.0/10"), 20 | netip.MustParsePrefix("127.0.0.0/8"), 21 | netip.MustParsePrefix("169.254.0.0/16"), 22 | netip.MustParsePrefix("172.16.0.0/12"), 23 | netip.MustParsePrefix("192.0.0.0/24"), 24 | netip.MustParsePrefix("192.0.2.0/24"), 25 | netip.MustParsePrefix("192.168.0.0/16"), 26 | netip.MustParsePrefix("198.18.0.0/15"), 27 | netip.MustParsePrefix("198.51.100.0/24"), 28 | netip.MustParsePrefix("203.0.113.0/24"), 29 | netip.MustParsePrefix("224.0.0.0/4"), 30 | netip.MustParsePrefix("240.0.0.0/4"), 31 | netip.MustParsePrefix("255.255.255.255/32"), 32 | netip.MustParsePrefix("::/128"), 33 | netip.MustParsePrefix("::1/128"), 34 | netip.MustParsePrefix("::ffff:0:0/96"), 35 | netip.MustParsePrefix("::/96"), 36 | netip.MustParsePrefix("100::/64"), 37 | netip.MustParsePrefix("2001:10::/28"), 38 | netip.MustParsePrefix("2001:db8::/32"), 39 | netip.MustParsePrefix("fc00::/7"), 40 | netip.MustParsePrefix("fe80::/10"), 41 | netip.MustParsePrefix("fec0::/10"), 42 | netip.MustParsePrefix("ff00::/8"), 43 | netip.MustParsePrefix("2002::/24"), 44 | netip.MustParsePrefix("2002:a00::/24"), 45 | netip.MustParsePrefix("2002:7f00::/24"), 46 | netip.MustParsePrefix("2002:a9fe::/32"), 47 | netip.MustParsePrefix("2002:ac10::/28"), 48 | netip.MustParsePrefix("2002:c000::/40"), 49 | netip.MustParsePrefix("2002:c000:200::/40"), 50 | netip.MustParsePrefix("2002:c0a8::/32"), 51 | netip.MustParsePrefix("2002:c612::/31"), 52 | netip.MustParsePrefix("2002:c633:6400::/40"), 53 | netip.MustParsePrefix("2002:cb00:7100::/40"), 54 | netip.MustParsePrefix("2002:e000::/20"), 55 | netip.MustParsePrefix("2002:f000::/20"), 56 | netip.MustParsePrefix("2002:ffff:ffff::/48"), 57 | netip.MustParsePrefix("2001::/40"), 58 | netip.MustParsePrefix("2001:0:a00::/40"), 59 | netip.MustParsePrefix("2001:0:7f00::/40"), 60 | netip.MustParsePrefix("2001:0:a9fe::/48"), 61 | netip.MustParsePrefix("2001:0:ac10::/44"), 62 | netip.MustParsePrefix("2001:0:c000::/56"), 63 | netip.MustParsePrefix("2001:0:c000:200::/56"), 64 | netip.MustParsePrefix("2001:0:c0a8::/48"), 65 | netip.MustParsePrefix("2001:0:c612::/47"), 66 | netip.MustParsePrefix("2001:0:c633:6400::/56"), 67 | netip.MustParsePrefix("2001:0:cb00:7100::/56"), 68 | netip.MustParsePrefix("2001:0:e000::/36"), 69 | netip.MustParsePrefix("2001:0:f000::/36"), 70 | netip.MustParsePrefix("2001:0:ffff:ffff::/64"), 71 | } 72 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 2.12.0 2 | 3 | - Add support for IPinfo Core API 4 | - Add support for IPinfo Plus API 5 | 6 | # 2.11.0 7 | 8 | - Add support for IPinfo Lite API 9 | 10 | # 2.10.0 11 | 12 | - Added support for looking up your v6 IP via `GetIPInfoV6`. 13 | 14 | # 2.9.4 15 | 16 | - Removing null values while printing in `yaml` format 17 | 18 | # 2.9.3 19 | 20 | - Added a `CountryFlagURL` field to `Core`. 21 | 22 | # 2.9.2 23 | 24 | - Custom error message on 429(Too many requests). 25 | - Check bogon locally. 26 | 27 | # 2.9.1 28 | 29 | - Fixed default useragent. 30 | - Fixed `GetIPInfoBatch` panic on empty token or invalid IP. 31 | 32 | # 2.9.0 33 | 34 | - Added an `CountryFlag` field to `Core`. 35 | - Added an `CountryCurrency` field to `Core`. 36 | - Added an `Continent` field to `Core`. 37 | 38 | # 2.8.0 39 | 40 | - Added an `IsEU` field to `Core`, which checks whether the IP geolocates to a 41 | country within the European Union (EU). 42 | 43 | # 2.7.0 44 | 45 | - Made batch operations limit their concurrency to 8 batches by default, but 46 | configurable. 47 | 48 | # 2.6.0 49 | 50 | - Added `Relay` and `Service` fields to `CorePrivacy`. 51 | - Added `Relay` field to `IPSummary.Privacy` and `PrivacyServices` to 52 | `IPSummary`. 53 | 54 | # 2.5.4 55 | 56 | - Fixed issue where disabling per-batch timeouts was impossible with negative 57 | numbers, contrary to what the documentation says. 58 | 59 | # 2.5.3 60 | 61 | - Dummy release to make up for a bug in 2.5.2. 62 | 63 | # 2.5.2 (skip this release) 64 | 65 | - Removed the IP list length constraints on `GetIPSummary`. 66 | This is because the underlying API has changed. 67 | 68 | # 2.5.1 69 | 70 | - Added the `IPSummary.Domains` field. 71 | 72 | # 2.5.0 73 | 74 | - Added versioned cache keys. 75 | This allows more reliable changes to cached data in the future without 76 | causing confusing incompatibilities. This should be transparent to the user. 77 | 78 | # 2.4.0 79 | 80 | - Added support for IP Map API. 81 | 82 | # 2.3.2 83 | 84 | - Added the `Core.Bogon` boolean field. 85 | 86 | # 2.3.1 87 | 88 | - Added more summary fields (carrier & mobile data). 89 | 90 | # 2.3.0 91 | 92 | - Added support for IP summary API. 93 | 94 | # 2.2.3 95 | 96 | - Added CSV tags for `Core` data for easier CSV marshaling. 97 | - Omit empty `Core` objects when encoding JSON. 98 | - Encode `Core.CountryName` and `Core.Abuse.CountryName` properly in JSON. 99 | 100 | # 2.2.2 101 | 102 | - Added a function `GetCountryName` to transform country code into full name. 103 | 104 | # 2.2.1 105 | 106 | - Added the `Core.Anycast` boolean field. 107 | 108 | # 2.2.0 109 | 110 | - The following functions are now private: 111 | - `Client.Do` 112 | - `Client.NewRequest` 113 | - `CheckResponse` 114 | - The following **new** functions now exist, which operate on the IPinfo 115 | `/batch` endpoint: 116 | - `Client.GetBatch` 117 | - `Client.GetIPInfoBatch` 118 | - `Client.GetIPStrInfoBatch` 119 | - `Client.GetASNDetailsBatch` 120 | - `ipinfo.GetBatch` 121 | - `ipinfo.GetIPInfoBatch` 122 | - `ipinfo.GetIPStrInfoBatch` 123 | - `ipinfo.GetASNDetailsBatch` 124 | 125 | # 2.1.1 126 | 127 | - Fixed go module path to have "v2" at the end as necessary. 128 | 129 | # 2.1.0 130 | 131 | - A new field `CountryName` was added to both `ASNDetails` and `Core`, which 132 | is the full name of the country abbreviated in the existing `Country` field. 133 | For example, if `Country == "PK"`, now `CountryName == "Pakistan"` exists. 134 | 135 | # 2.0.0 136 | 137 | - The API for creating a client and making certain requests has changed and has 138 | been made generally simpler. Please see the documentation for exact details. 139 | - go.mod now included. 140 | - All new API data types are now available for the Core & ASN APIs. 141 | - Cache interface now requires implementors to be concurrency-safe. 142 | -------------------------------------------------------------------------------- /ipinfo/lite.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "io" 7 | "net" 8 | "net/http" 9 | "net/netip" 10 | "net/url" 11 | "strings" 12 | ) 13 | 14 | const ( 15 | defaultLiteBaseURL = "https://api.ipinfo.io/lite/" 16 | ) 17 | 18 | // LiteClient is a client for the IPinfo Lite API. 19 | type LiteClient struct { 20 | // HTTP client used to communicate with the API. 21 | client *http.Client 22 | 23 | // Base URL for API requests. 24 | BaseURL *url.URL 25 | 26 | // User agent used when communicating with the IPinfo API. 27 | UserAgent string 28 | 29 | // Cache interface implementation to prevent API quota overuse. 30 | Cache *Cache 31 | 32 | // The API token used for authorization. 33 | Token string 34 | } 35 | 36 | // Lite represents the response from the IPinfo Lite API. 37 | type Lite struct { 38 | IP net.IP `json:"ip"` 39 | ASN string `json:"asn"` 40 | ASName string `json:"as_name"` 41 | ASDomain string `json:"as_domain"` 42 | CountryCode string `json:"country_code"` 43 | Country string `json:"country"` 44 | ContinentCode string `json:"continent_code"` 45 | Continent string `json:"continent"` 46 | Bogon bool `json:"bogon"` 47 | 48 | // Extended fields using the same country data as Core API 49 | CountryName string `json:"-"` 50 | CountryFlag CountryFlag `json:"-"` 51 | CountryFlagURL string `json:"-"` 52 | CountryCurrency CountryCurrency `json:"-"` 53 | ContinentInfo Continent `json:"-"` 54 | IsEU bool `json:"-"` 55 | } 56 | 57 | func (v *Lite) setCountryName() { 58 | if v.CountryCode != "" { 59 | v.CountryName = GetCountryName(v.CountryCode) 60 | v.IsEU = IsEU(v.CountryCode) 61 | v.CountryFlag.Emoji = GetCountryFlagEmoji(v.CountryCode) 62 | v.CountryFlag.Unicode = GetCountryFlagUnicode(v.CountryCode) 63 | v.CountryFlagURL = GetCountryFlagURL(v.CountryCode) 64 | v.CountryCurrency.Code = GetCountryCurrencyCode(v.CountryCode) 65 | v.CountryCurrency.Symbol = GetCountryCurrencySymbol(v.CountryCode) 66 | v.ContinentInfo.Code = GetContinentCode(v.CountryCode) 67 | v.ContinentInfo.Name = GetContinentName(v.CountryCode) 68 | } 69 | } 70 | 71 | // NewLiteClient creates a new IPinfo Lite API client. 72 | func NewLiteClient(httpClient *http.Client, cache *Cache, token string) *LiteClient { 73 | if httpClient == nil { 74 | httpClient = http.DefaultClient 75 | } 76 | 77 | baseURL, _ := url.Parse(defaultLiteBaseURL) 78 | return &LiteClient{ 79 | client: httpClient, 80 | BaseURL: baseURL, 81 | UserAgent: defaultUserAgent, 82 | Cache: cache, 83 | Token: token, 84 | } 85 | } 86 | 87 | // GetIPInfo returns the lite details for the specified IP. 88 | func (c *LiteClient) GetIPInfo(ip net.IP) (*Lite, error) { 89 | if ip != nil && isBogon(netip.MustParseAddr(ip.String())) { 90 | bogonResponse := new(Lite) 91 | bogonResponse.Bogon = true 92 | bogonResponse.IP = ip 93 | return bogonResponse, nil 94 | } 95 | relUrl := "me" 96 | if ip != nil { 97 | relUrl = ip.String() 98 | } 99 | 100 | if c.Cache != nil { 101 | if res, err := c.Cache.Get(cacheKey(relUrl)); err == nil { 102 | return res.(*Lite), nil 103 | } 104 | } 105 | 106 | req, err := c.newRequest(nil, "GET", relUrl, nil) 107 | if err != nil { 108 | return nil, err 109 | } 110 | 111 | res := new(Lite) 112 | if _, err := c.do(req, res); err != nil { 113 | return nil, err 114 | } 115 | 116 | res.setCountryName() 117 | 118 | if c.Cache != nil { 119 | if err := c.Cache.Set(cacheKey(relUrl), res); err != nil { 120 | return res, err 121 | } 122 | } 123 | 124 | return res, nil 125 | } 126 | 127 | func (c *LiteClient) newRequest(ctx context.Context, 128 | method string, 129 | urlStr string, 130 | body io.Reader, 131 | ) (*http.Request, error) { 132 | if ctx == nil { 133 | ctx = context.Background() 134 | } 135 | 136 | u := new(url.URL) 137 | baseURL := c.BaseURL 138 | if rel, err := url.Parse(urlStr); err == nil { 139 | u = baseURL.ResolveReference(rel) 140 | } else if strings.ContainsRune(urlStr, ':') { 141 | // IPv6 strings fail to parse as URLs, so let's add it as a URL Path. 142 | *u = *baseURL 143 | u.Path += urlStr 144 | } else { 145 | return nil, err 146 | } 147 | 148 | // get `http` package request object. 149 | req, err := http.NewRequestWithContext(ctx, method, u.String(), body) 150 | if err != nil { 151 | return nil, err 152 | } 153 | 154 | // set common headers. 155 | req.Header.Set("Accept", "application/json") 156 | if c.UserAgent != "" { 157 | req.Header.Set("User-Agent", c.UserAgent) 158 | } 159 | if c.Token != "" { 160 | req.Header.Set("Authorization", "Bearer "+c.Token) 161 | } 162 | 163 | return req, nil 164 | } 165 | 166 | func (c *LiteClient) do( 167 | req *http.Request, 168 | v interface{}, 169 | ) (*http.Response, error) { 170 | resp, err := c.client.Do(req) 171 | if err != nil { 172 | return nil, err 173 | } 174 | defer resp.Body.Close() 175 | 176 | err = checkResponse(resp) 177 | if err != nil { 178 | // even though there was an error, we still return the response 179 | // in case the caller wants to inspect it further 180 | return resp, err 181 | } 182 | 183 | if v != nil { 184 | if w, ok := v.(io.Writer); ok { 185 | io.Copy(w, resp.Body) 186 | } else { 187 | err = json.NewDecoder(resp.Body).Decode(v) 188 | if err == io.EOF { 189 | // ignore EOF errors caused by empty response body 190 | err = nil 191 | } 192 | } 193 | } 194 | 195 | return resp, err 196 | } 197 | 198 | // GetIPInfo returns the details for the specified IP. 199 | func GetIPInfoLite(ip net.IP) (*Lite, error) { 200 | return DefaultLiteClient.GetIPInfo(ip) 201 | } 202 | -------------------------------------------------------------------------------- /ipinfo/core_new.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "io" 7 | "net" 8 | "net/http" 9 | "net/netip" 10 | "net/url" 11 | "strings" 12 | ) 13 | 14 | const ( 15 | defaultCoreBaseURL = "https://api.ipinfo.io/lookup/" 16 | ) 17 | 18 | // CoreClient is a client for the IPinfo Core API. 19 | type CoreClient struct { 20 | // HTTP client used to communicate with the API. 21 | client *http.Client 22 | 23 | // Base URL for API requests. 24 | BaseURL *url.URL 25 | 26 | // User agent used when communicating with the IPinfo API. 27 | UserAgent string 28 | 29 | // Cache interface implementation to prevent API quota overuse. 30 | Cache *Cache 31 | 32 | // The API token used for authorization. 33 | Token string 34 | } 35 | 36 | // CoreResponse represents the response from the IPinfo Core API /lookup endpoint. 37 | type CoreResponse struct { 38 | IP net.IP `json:"ip"` 39 | Bogon bool `json:"bogon,omitempty"` 40 | Geo *CoreGeo `json:"geo,omitempty"` 41 | AS *CoreAS `json:"as,omitempty"` 42 | IsAnonymous bool `json:"is_anonymous"` 43 | IsAnycast bool `json:"is_anycast"` 44 | IsHosting bool `json:"is_hosting"` 45 | IsMobile bool `json:"is_mobile"` 46 | IsSatellite bool `json:"is_satellite"` 47 | } 48 | 49 | // CoreGeo represents the geo object in Core API response. 50 | type CoreGeo struct { 51 | City string `json:"city,omitempty"` 52 | Region string `json:"region,omitempty"` 53 | RegionCode string `json:"region_code,omitempty"` 54 | Country string `json:"country,omitempty"` 55 | CountryCode string `json:"country_code,omitempty"` 56 | Continent string `json:"continent,omitempty"` 57 | ContinentCode string `json:"continent_code,omitempty"` 58 | Latitude float64 `json:"latitude"` 59 | Longitude float64 `json:"longitude"` 60 | Timezone string `json:"timezone,omitempty"` 61 | PostalCode string `json:"postal_code,omitempty"` 62 | 63 | // Extended fields using the same country data as legacy Core API 64 | CountryName string `json:"-"` 65 | IsEU bool `json:"-"` 66 | CountryFlag CountryFlag `json:"-"` 67 | CountryFlagURL string `json:"-"` 68 | CountryCurrency CountryCurrency `json:"-"` 69 | ContinentInfo Continent `json:"-"` 70 | } 71 | 72 | // CoreAS represents the AS object in Core API response. 73 | type CoreAS struct { 74 | ASN string `json:"asn"` 75 | Name string `json:"name"` 76 | Domain string `json:"domain"` 77 | Type string `json:"type"` 78 | } 79 | 80 | func (v *CoreResponse) enrichGeo() { 81 | if v.Geo != nil && v.Geo.CountryCode != "" { 82 | v.Geo.CountryName = GetCountryName(v.Geo.CountryCode) 83 | v.Geo.IsEU = IsEU(v.Geo.CountryCode) 84 | v.Geo.CountryFlag.Emoji = GetCountryFlagEmoji(v.Geo.CountryCode) 85 | v.Geo.CountryFlag.Unicode = GetCountryFlagUnicode(v.Geo.CountryCode) 86 | v.Geo.CountryFlagURL = GetCountryFlagURL(v.Geo.CountryCode) 87 | v.Geo.CountryCurrency.Code = GetCountryCurrencyCode(v.Geo.CountryCode) 88 | v.Geo.CountryCurrency.Symbol = GetCountryCurrencySymbol(v.Geo.CountryCode) 89 | v.Geo.ContinentInfo.Code = GetContinentCode(v.Geo.CountryCode) 90 | v.Geo.ContinentInfo.Name = GetContinentName(v.Geo.CountryCode) 91 | } 92 | } 93 | 94 | // NewCoreClient creates a new IPinfo Core API client. 95 | func NewCoreClient(httpClient *http.Client, cache *Cache, token string) *CoreClient { 96 | if httpClient == nil { 97 | httpClient = http.DefaultClient 98 | } 99 | 100 | baseURL, _ := url.Parse(defaultCoreBaseURL) 101 | return &CoreClient{ 102 | client: httpClient, 103 | BaseURL: baseURL, 104 | UserAgent: defaultUserAgent, 105 | Cache: cache, 106 | Token: token, 107 | } 108 | } 109 | 110 | // GetIPInfo returns the Core details for the specified IP. 111 | func (c *CoreClient) GetIPInfo(ip net.IP) (*CoreResponse, error) { 112 | if ip != nil && isBogon(netip.MustParseAddr(ip.String())) { 113 | bogonResponse := new(CoreResponse) 114 | bogonResponse.Bogon = true 115 | bogonResponse.IP = ip 116 | return bogonResponse, nil 117 | } 118 | relUrl := "" 119 | if ip != nil { 120 | relUrl = ip.String() 121 | } 122 | 123 | if c.Cache != nil { 124 | if res, err := c.Cache.Get(cacheKey(relUrl)); err == nil { 125 | return res.(*CoreResponse), nil 126 | } 127 | } 128 | 129 | req, err := c.newRequest(nil, "GET", relUrl, nil) 130 | if err != nil { 131 | return nil, err 132 | } 133 | 134 | res := new(CoreResponse) 135 | if _, err := c.do(req, res); err != nil { 136 | return nil, err 137 | } 138 | 139 | res.enrichGeo() 140 | 141 | if c.Cache != nil { 142 | if err := c.Cache.Set(cacheKey(relUrl), res); err != nil { 143 | return res, err 144 | } 145 | } 146 | 147 | return res, nil 148 | } 149 | 150 | func (c *CoreClient) newRequest(ctx context.Context, 151 | method string, 152 | urlStr string, 153 | body io.Reader, 154 | ) (*http.Request, error) { 155 | if ctx == nil { 156 | ctx = context.Background() 157 | } 158 | 159 | u := new(url.URL) 160 | baseURL := c.BaseURL 161 | if rel, err := url.Parse(urlStr); err == nil { 162 | u = baseURL.ResolveReference(rel) 163 | } else if strings.ContainsRune(urlStr, ':') { 164 | // IPv6 strings fail to parse as URLs, so let's add it as a URL Path. 165 | *u = *baseURL 166 | u.Path += urlStr 167 | } else { 168 | return nil, err 169 | } 170 | 171 | // get `http` package request object. 172 | req, err := http.NewRequestWithContext(ctx, method, u.String(), body) 173 | if err != nil { 174 | return nil, err 175 | } 176 | 177 | // set common headers. 178 | req.Header.Set("Accept", "application/json") 179 | if c.UserAgent != "" { 180 | req.Header.Set("User-Agent", c.UserAgent) 181 | } 182 | if c.Token != "" { 183 | req.Header.Set("Authorization", "Bearer "+c.Token) 184 | } 185 | 186 | return req, nil 187 | } 188 | 189 | func (c *CoreClient) do( 190 | req *http.Request, 191 | v interface{}, 192 | ) (*http.Response, error) { 193 | resp, err := c.client.Do(req) 194 | if err != nil { 195 | return nil, err 196 | } 197 | defer resp.Body.Close() 198 | 199 | err = checkResponse(resp) 200 | if err != nil { 201 | // even though there was an error, we still return the response 202 | // in case the caller wants to inspect it further 203 | return resp, err 204 | } 205 | 206 | if v != nil { 207 | if w, ok := v.(io.Writer); ok { 208 | io.Copy(w, resp.Body) 209 | } else { 210 | err = json.NewDecoder(resp.Body).Decode(v) 211 | if err == io.EOF { 212 | // ignore EOF errors caused by empty response body 213 | err = nil 214 | } 215 | } 216 | } 217 | 218 | return resp, err 219 | } 220 | 221 | // GetIPInfoCore returns the Core details for the specified IP. 222 | func GetIPInfoCore(ip net.IP) (*CoreResponse, error) { 223 | return DefaultCoreClient.GetIPInfo(ip) 224 | } 225 | -------------------------------------------------------------------------------- /ipinfo/client.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "net/http" 9 | "net/url" 10 | "strings" 11 | ) 12 | 13 | const ( 14 | defaultBaseURL = "https://ipinfo.io/" 15 | defaultBaseURLIPv6 = "https://v6.ipinfo.io/" 16 | defaultUserAgent = "IPinfoClient/Go/2.12.0" 17 | ) 18 | 19 | // A Client is the main handler to communicate with the IPinfo API. 20 | type Client struct { 21 | // HTTP client used to communicate with the API. 22 | client *http.Client 23 | 24 | // Base URL for API requests. BaseURL should always be specified with a 25 | // trailing slash. 26 | BaseURL *url.URL 27 | 28 | // User agent used when communicating with the IPinfo API. 29 | UserAgent string 30 | 31 | // Cache interface implementation to prevent API quota overuse for 32 | // identical requests. 33 | Cache *Cache 34 | 35 | // The API token used for authorization for more data and higher limits. 36 | Token string 37 | } 38 | 39 | // NewClient returns a new IPinfo API client. 40 | // 41 | // If `httpClient` is nil, `http.DefaultClient` will be used. 42 | // 43 | // If `cache` is nil, no cache is automatically assigned. You may set one later 44 | // at any time with `client.SetCache`. 45 | // 46 | // If `token` is empty, the API will be queried without any token. You may set 47 | // one later at any time with `client.SetToken`. 48 | func NewClient( 49 | httpClient *http.Client, 50 | cache *Cache, 51 | token string, 52 | ) *Client { 53 | if httpClient == nil { 54 | httpClient = http.DefaultClient 55 | } 56 | 57 | baseURL, _ := url.Parse(defaultBaseURL) 58 | return &Client{ 59 | client: httpClient, 60 | BaseURL: baseURL, 61 | UserAgent: defaultUserAgent, 62 | Cache: cache, 63 | Token: token, 64 | } 65 | } 66 | 67 | // newRequest for IPV4 68 | func (c *Client) newRequest( 69 | ctx context.Context, 70 | method string, 71 | urlStr string, 72 | body io.Reader, 73 | ) (*http.Request, error) { 74 | return c.newRequestBase(ctx, method, urlStr, body, false) 75 | } 76 | 77 | // newRequest for IPV6 78 | func (c *Client) newRequestV6( 79 | ctx context.Context, 80 | method string, 81 | urlStr string, 82 | body io.Reader, 83 | ) (*http.Request, error) { 84 | return c.newRequestBase(ctx, method, urlStr, body, true) 85 | } 86 | 87 | // `newRequest` creates an API request. A relative URL can be provided in 88 | // urlStr, in which case it is resolved relative to the BaseURL of the Client. 89 | // Relative URLs should always be specified without a preceding slash. 90 | func (c *Client) newRequestBase( 91 | ctx context.Context, 92 | method string, 93 | urlStr string, 94 | body io.Reader, 95 | useIPv6 bool, 96 | ) (*http.Request, error) { 97 | if ctx == nil { 98 | ctx = context.Background() 99 | } 100 | 101 | u := new(url.URL) 102 | 103 | baseURL := c.BaseURL 104 | if useIPv6 { 105 | baseURL, _ = url.Parse(defaultBaseURLIPv6) 106 | } 107 | 108 | // get final URL path. 109 | if rel, err := url.Parse(urlStr); err == nil { 110 | u = baseURL.ResolveReference(rel) 111 | } else if strings.ContainsRune(urlStr, ':') { 112 | // IPv6 strings fail to parse as URLs, so let's add it as a URL Path. 113 | *u = *baseURL 114 | u.Path += urlStr 115 | } else { 116 | return nil, err 117 | } 118 | 119 | // get `http` package request object. 120 | req, err := http.NewRequestWithContext(ctx, method, u.String(), body) 121 | if err != nil { 122 | return nil, err 123 | } 124 | 125 | // set common headers. 126 | req.Header.Set("Accept", "application/json") 127 | if c.UserAgent != "" { 128 | req.Header.Set("User-Agent", c.UserAgent) 129 | } 130 | if c.Token != "" { 131 | req.Header.Set("Authorization", "Bearer "+c.Token) 132 | } 133 | 134 | return req, nil 135 | } 136 | 137 | // `do` sends an API request and returns the API response. The API response is 138 | // JSON decoded and stored in the value pointed to by v, or returned as an 139 | // error if an API error has occurred. If v implements the io.Writer interface, 140 | // the raw response body will be written to v, without attempting to first 141 | // decode it. 142 | func (c *Client) do( 143 | req *http.Request, 144 | v interface{}, 145 | ) (*http.Response, error) { 146 | resp, err := c.client.Do(req) 147 | if err != nil { 148 | return nil, err 149 | } 150 | defer resp.Body.Close() 151 | 152 | err = checkResponse(resp) 153 | if err != nil { 154 | // even though there was an error, we still return the response 155 | // in case the caller wants to inspect it further 156 | return resp, err 157 | } 158 | 159 | if v != nil { 160 | if w, ok := v.(io.Writer); ok { 161 | io.Copy(w, resp.Body) 162 | } else { 163 | err = json.NewDecoder(resp.Body).Decode(v) 164 | if err == io.EOF { 165 | // ignore EOF errors caused by empty response body 166 | err = nil 167 | } 168 | } 169 | } 170 | 171 | return resp, err 172 | } 173 | 174 | // An ErrorResponse reports an error caused by an API request. 175 | type ErrorResponse struct { 176 | // HTTP response that caused this error 177 | Response *http.Response 178 | 179 | // Error structure returned by the IPinfo Core API. 180 | Status string `json:"status"` 181 | Err struct { 182 | Title string `json:"title"` 183 | Message string `json:"message"` 184 | } `json:"error"` 185 | } 186 | 187 | func (r *ErrorResponse) Error() string { 188 | if r.Response.StatusCode == http.StatusTooManyRequests { 189 | return fmt.Sprintf("%v %v: %d You've hit the daily limit for the unauthenticated API. Please visit https://ipinfo.io/signup to get 50k requests per month for free.", 190 | r.Response.Request.Method, r.Response.Request.URL, 191 | r.Response.StatusCode) 192 | } 193 | return fmt.Sprintf("%v %v: %d %v", 194 | r.Response.Request.Method, r.Response.Request.URL, 195 | r.Response.StatusCode, r.Err) 196 | } 197 | 198 | // `checkResponse` checks the API response for errors, and returns them if 199 | // present. A response is considered an error if it has a status code outside 200 | // the 200 range. 201 | func checkResponse(r *http.Response) error { 202 | if c := r.StatusCode; 200 <= c && c <= 299 { 203 | return nil 204 | } 205 | errorResponse := &ErrorResponse{Response: r} 206 | data, err := io.ReadAll(r.Body) 207 | if err == nil && data != nil { 208 | json.Unmarshal(data, errorResponse) 209 | } 210 | return errorResponse 211 | } 212 | 213 | /* SetCache */ 214 | 215 | // SetCache assigns a cache to the package-level client. 216 | func SetCache(cache *Cache) { 217 | DefaultClient.SetCache(cache) 218 | } 219 | 220 | // SetCache assigns a cache to the client `c`. 221 | func (c *Client) SetCache(cache *Cache) { 222 | c.Cache = cache 223 | } 224 | 225 | /* SetToken */ 226 | 227 | // SetToken assigns a token to the package-level client. 228 | func SetToken(token string) { 229 | DefaultClient.SetToken(token) 230 | } 231 | 232 | // SetToken assigns a token to the client `c`. 233 | func (c *Client) SetToken(token string) { 234 | c.Token = token 235 | } 236 | -------------------------------------------------------------------------------- /ipinfo/plus.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "io" 7 | "net" 8 | "net/http" 9 | "net/netip" 10 | "net/url" 11 | "strings" 12 | ) 13 | 14 | const ( 15 | defaultPlusBaseURL = "https://api.ipinfo.io/lookup/" 16 | ) 17 | 18 | // PlusClient is a client for the IPinfo Plus API. 19 | type PlusClient struct { 20 | // HTTP client used to communicate with the API. 21 | client *http.Client 22 | 23 | // Base URL for API requests. 24 | BaseURL *url.URL 25 | 26 | // User agent used when communicating with the IPinfo API. 27 | UserAgent string 28 | 29 | // Cache interface implementation to prevent API quota overuse. 30 | Cache *Cache 31 | 32 | // The API token used for authorization. 33 | Token string 34 | } 35 | 36 | // Plus represents the response from the IPinfo Plus API /lookup endpoint. 37 | type Plus struct { 38 | IP net.IP `json:"ip"` 39 | Hostname string `json:"hostname,omitempty"` 40 | Bogon bool `json:"bogon,omitempty"` 41 | Geo *PlusGeo `json:"geo,omitempty"` 42 | AS *PlusAS `json:"as,omitempty"` 43 | Mobile *PlusMobile `json:"mobile,omitempty"` 44 | Anonymous *PlusAnonymous `json:"anonymous,omitempty"` 45 | IsAnonymous bool `json:"is_anonymous"` 46 | IsAnycast bool `json:"is_anycast"` 47 | IsHosting bool `json:"is_hosting"` 48 | IsMobile bool `json:"is_mobile"` 49 | IsSatellite bool `json:"is_satellite"` 50 | Abuse *PlusAbuse `json:"abuse,omitempty"` 51 | Company *PlusCompany `json:"company,omitempty"` 52 | Privacy *PlusPrivacy `json:"privacy,omitempty"` 53 | Domains *PlusDomains `json:"domains,omitempty"` 54 | } 55 | 56 | // PlusGeo represents the geo object in Plus API response. 57 | type PlusGeo struct { 58 | City string `json:"city,omitempty"` 59 | Region string `json:"region,omitempty"` 60 | RegionCode string `json:"region_code,omitempty"` 61 | Country string `json:"country,omitempty"` 62 | CountryCode string `json:"country_code,omitempty"` 63 | Continent string `json:"continent,omitempty"` 64 | ContinentCode string `json:"continent_code,omitempty"` 65 | Latitude float64 `json:"latitude"` 66 | Longitude float64 `json:"longitude"` 67 | Timezone string `json:"timezone,omitempty"` 68 | PostalCode string `json:"postal_code,omitempty"` 69 | DMACode string `json:"dma_code,omitempty"` 70 | GeonameID string `json:"geoname_id,omitempty"` 71 | Radius int `json:"radius"` 72 | LastChanged string `json:"last_changed,omitempty"` 73 | 74 | // Extended fields using the same country data as legacy Core API 75 | CountryName string `json:"-"` 76 | IsEU bool `json:"-"` 77 | CountryFlag CountryFlag `json:"-"` 78 | CountryFlagURL string `json:"-"` 79 | CountryCurrency CountryCurrency `json:"-"` 80 | ContinentInfo Continent `json:"-"` 81 | } 82 | 83 | // PlusAS represents the AS object in Plus API response. 84 | type PlusAS struct { 85 | ASN string `json:"asn"` 86 | Name string `json:"name"` 87 | Domain string `json:"domain"` 88 | Type string `json:"type"` 89 | LastChanged string `json:"last_changed,omitempty"` 90 | } 91 | 92 | // PlusMobile represents the mobile object in Plus API response. 93 | type PlusMobile struct { 94 | Name string `json:"name,omitempty"` 95 | MCC string `json:"mcc,omitempty"` 96 | MNC string `json:"mnc,omitempty"` 97 | } 98 | 99 | // PlusAnonymous represents the anonymous object in Plus API response. 100 | type PlusAnonymous struct { 101 | IsProxy bool `json:"is_proxy"` 102 | IsRelay bool `json:"is_relay"` 103 | IsTor bool `json:"is_tor"` 104 | IsVPN bool `json:"is_vpn"` 105 | Name string `json:"name,omitempty"` 106 | } 107 | 108 | // PlusAbuse represents the abuse object in Plus API response. 109 | type PlusAbuse struct { 110 | Address string `json:"address,omitempty"` 111 | Country string `json:"country,omitempty"` 112 | CountryName string `json:"country_name,omitempty"` 113 | Email string `json:"email,omitempty"` 114 | Name string `json:"name,omitempty"` 115 | Network string `json:"network,omitempty"` 116 | Phone string `json:"phone,omitempty"` 117 | } 118 | 119 | // PlusCompany represents the company object in Plus API response. 120 | type PlusCompany struct { 121 | Name string `json:"name,omitempty"` 122 | Domain string `json:"domain,omitempty"` 123 | Type string `json:"type,omitempty"` 124 | } 125 | 126 | // PlusPrivacy represents the privacy object in Plus API response. 127 | type PlusPrivacy struct { 128 | VPN bool `json:"vpn"` 129 | Proxy bool `json:"proxy"` 130 | Tor bool `json:"tor"` 131 | Relay bool `json:"relay"` 132 | Hosting bool `json:"hosting"` 133 | Service string `json:"service,omitempty"` 134 | } 135 | 136 | // PlusDomains represents the domains object in Plus API response. 137 | type PlusDomains struct { 138 | IP string `json:"ip,omitempty"` 139 | Total uint64 `json:"total"` 140 | Domains []string `json:"domains,omitempty"` 141 | } 142 | 143 | func (v *Plus) enrichGeo() { 144 | if v.Geo != nil && v.Geo.CountryCode != "" { 145 | v.Geo.CountryName = GetCountryName(v.Geo.CountryCode) 146 | v.Geo.IsEU = IsEU(v.Geo.CountryCode) 147 | v.Geo.CountryFlag.Emoji = GetCountryFlagEmoji(v.Geo.CountryCode) 148 | v.Geo.CountryFlag.Unicode = GetCountryFlagUnicode(v.Geo.CountryCode) 149 | v.Geo.CountryFlagURL = GetCountryFlagURL(v.Geo.CountryCode) 150 | v.Geo.CountryCurrency.Code = GetCountryCurrencyCode(v.Geo.CountryCode) 151 | v.Geo.CountryCurrency.Symbol = GetCountryCurrencySymbol(v.Geo.CountryCode) 152 | v.Geo.ContinentInfo.Code = GetContinentCode(v.Geo.CountryCode) 153 | v.Geo.ContinentInfo.Name = GetContinentName(v.Geo.CountryCode) 154 | } 155 | if v.Abuse != nil && v.Abuse.Country != "" { 156 | v.Abuse.CountryName = GetCountryName(v.Abuse.Country) 157 | } 158 | } 159 | 160 | // NewPlusClient creates a new IPinfo Plus API client. 161 | func NewPlusClient(httpClient *http.Client, cache *Cache, token string) *PlusClient { 162 | if httpClient == nil { 163 | httpClient = http.DefaultClient 164 | } 165 | 166 | baseURL, _ := url.Parse(defaultPlusBaseURL) 167 | return &PlusClient{ 168 | client: httpClient, 169 | BaseURL: baseURL, 170 | UserAgent: defaultUserAgent, 171 | Cache: cache, 172 | Token: token, 173 | } 174 | } 175 | 176 | // GetIPInfo returns the Plus details for the specified IP. 177 | func (c *PlusClient) GetIPInfo(ip net.IP) (*Plus, error) { 178 | if ip != nil && isBogon(netip.MustParseAddr(ip.String())) { 179 | bogonResponse := new(Plus) 180 | bogonResponse.Bogon = true 181 | bogonResponse.IP = ip 182 | return bogonResponse, nil 183 | } 184 | relUrl := "" 185 | if ip != nil { 186 | relUrl = ip.String() 187 | } 188 | 189 | if c.Cache != nil { 190 | if res, err := c.Cache.Get(cacheKey(relUrl)); err == nil { 191 | return res.(*Plus), nil 192 | } 193 | } 194 | 195 | req, err := c.newRequest(nil, "GET", relUrl, nil) 196 | if err != nil { 197 | return nil, err 198 | } 199 | 200 | res := new(Plus) 201 | if _, err := c.do(req, res); err != nil { 202 | return nil, err 203 | } 204 | 205 | res.enrichGeo() 206 | 207 | if c.Cache != nil { 208 | if err := c.Cache.Set(cacheKey(relUrl), res); err != nil { 209 | return res, err 210 | } 211 | } 212 | 213 | return res, nil 214 | } 215 | 216 | func (c *PlusClient) newRequest(ctx context.Context, 217 | method string, 218 | urlStr string, 219 | body io.Reader, 220 | ) (*http.Request, error) { 221 | if ctx == nil { 222 | ctx = context.Background() 223 | } 224 | 225 | u := new(url.URL) 226 | baseURL := c.BaseURL 227 | if rel, err := url.Parse(urlStr); err == nil { 228 | u = baseURL.ResolveReference(rel) 229 | } else if strings.ContainsRune(urlStr, ':') { 230 | // IPv6 strings fail to parse as URLs, so let's add it as a URL Path. 231 | *u = *baseURL 232 | u.Path += urlStr 233 | } else { 234 | return nil, err 235 | } 236 | 237 | // get `http` package request object. 238 | req, err := http.NewRequestWithContext(ctx, method, u.String(), body) 239 | if err != nil { 240 | return nil, err 241 | } 242 | 243 | // set common headers. 244 | req.Header.Set("Accept", "application/json") 245 | if c.UserAgent != "" { 246 | req.Header.Set("User-Agent", c.UserAgent) 247 | } 248 | if c.Token != "" { 249 | req.Header.Set("Authorization", "Bearer "+c.Token) 250 | } 251 | 252 | return req, nil 253 | } 254 | 255 | func (c *PlusClient) do( 256 | req *http.Request, 257 | v interface{}, 258 | ) (*http.Response, error) { 259 | resp, err := c.client.Do(req) 260 | if err != nil { 261 | return nil, err 262 | } 263 | defer resp.Body.Close() 264 | 265 | err = checkResponse(resp) 266 | if err != nil { 267 | // even though there was an error, we still return the response 268 | // in case the caller wants to inspect it further 269 | return resp, err 270 | } 271 | 272 | if v != nil { 273 | if w, ok := v.(io.Writer); ok { 274 | io.Copy(w, resp.Body) 275 | } else { 276 | err = json.NewDecoder(resp.Body).Decode(v) 277 | if err == io.EOF { 278 | // ignore EOF errors caused by empty response body 279 | err = nil 280 | } 281 | } 282 | } 283 | 284 | return resp, err 285 | } 286 | 287 | // GetIPInfoPlus returns the Plus details for the specified IP. 288 | func GetIPInfoPlus(ip net.IP) (*Plus, error) { 289 | return DefaultPlusClient.GetIPInfo(ip) 290 | } 291 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [IPinfo](https://ipinfo.io/) IPinfo Go Client Library 2 | 3 | [![License](http://img.shields.io/:license-apache-blue.svg)](LICENSE) 4 | [![Go Reference](https://pkg.go.dev/badge/github.com/ipinfo/go/v2/ipinfo.svg)](https://pkg.go.dev/github.com/ipinfo/go/v2/ipinfo) 5 | 6 | This is the official Go client library for the [IPinfo.io](https://ipinfo.io) IP address API, allowing you to look up your own IP address, or get any of the following details for other IP addresses: 7 | 8 | - [IP to Geolocation](https://ipinfo.io/ip-geolocation-api) (city, region, country, postal code, latitude, and longitude) 9 | - [IP to ASN](https://ipinfo.io/asn-api) (ISP or network operator, associated domain name, and type, such as business, hosting, or company) 10 | - [IP to Company](https://ipinfo.io/ip-company-api) (the name and domain of the business that uses the IP address) 11 | - [IP to Carrier](https://ipinfo.io/ip-carrier-api) (the name of the mobile carrier and MNC and MCC for that carrier if the IP is used exclusively for mobile traffic) 12 | 13 | Check all the data we have for your IP address [here](https://ipinfo.io/what-is-my-ip). 14 | 15 | 16 | - [Getting Started](#getting-started) 17 | - [Installation](#installation) 18 | - [Quickstart](#quickstart) 19 | - [Authentication](#authentication) 20 | - [Internationalization](#internationalization) 21 | - [Country Name](#country-name) 22 | - [European Union (EU) Country](#european-union-eu-country) 23 | - [Country Flag](#country-flag) 24 | - [Country Currency](#country-currency) 25 | - [Continent](#continent) 26 | - [Map IP Address](#map-ip-address) 27 | - [Summarize IP Address](#summarize-ip-address) 28 | - [Caching](#caching) 29 | - [Batch Operations / Bulk Lookup](#batch-operations--bulk-lookup) 30 | - [Other Libraries](#other-libraries) 31 | - [About IPinfo](#about-ipinfo) 32 | 33 | # Getting Started 34 | 35 | 36 | You'll need an IPinfo API access token, which you can get by signing up for a free account at [https://ipinfo.io/signup](https://ipinfo.io/signup). 37 | 38 | The free plan is limited to 50,000 requests per month, and doesn't include some of the data fields such as IP type and company data. To enable all the data fields and additional request volumes see [https://ipinfo.io/pricing](https://ipinfo.io/pricing) 39 | 40 | You can find the full package-level documentation here: https://pkg.go.dev/github.com/ipinfo/go/v2/ipinfo 41 | 42 | The library also supports the Lite API, see the [Lite API section](#lite-api) for more info. 43 | 44 | ## Installation 45 | 46 | ```bash 47 | go get github.com/ipinfo/go/v2/ipinfo 48 | ``` 49 | 50 | ## Quickstart 51 | 52 | Basic usage of the package. 53 | 54 | 55 | ```go 56 | package main 57 | 58 | import ( 59 | "fmt" 60 | "log" 61 | "net" 62 | "github.com/ipinfo/go/v2/ipinfo" 63 | ) 64 | 65 | func main() { 66 | const token = "YOUR_TOKEN" 67 | 68 | // params: httpClient, cache, token. `http.DefaultClient` and no cache will be used in case of `nil`. 69 | client := ipinfo.NewClient(nil, nil, token) 70 | 71 | const ip_address = "8.8.8.8" 72 | info, err := client.GetIPInfo(net.ParseIP(ip_address)) 73 | 74 | if err != nil { 75 | log.Fatal(err) 76 | } 77 | 78 | fmt.Println(info) 79 | // Output: {8.8.8.8 dns.google false true Mountain View California US United States... 80 | } 81 | ``` 82 | 83 | This data is available even on our free tier which includes up to 50,000 IP geolocation requests per month. 84 | 85 | # Authentication 86 | 87 | The IPinfo Go library can be authenticated with your IPinfo API access token, which is passed as the third positional argument of the `ipinfo.NewClient()` method. Your IPInfo access token can be found in the account section of IPinfo's website after you have signed in: https://ipinfo.io/account/token 88 | 89 | ```go 90 | const token = "YOUR_TOKEN" 91 | // params: httpClient, cache, token. `http.DefaultClient` and no cache will be used in case of `nil`. 92 | client := ipinfo.NewClient(nil, nil, token) 93 | ``` 94 | 95 | # Internationalization 96 | 97 | ## Country Name 98 | 99 | `info.Country` returns the ISO 3166 country code and `info.CountryName` returns the entire conuntry name: 100 | 101 | ```go 102 | fmt.Println(info.Country) 103 | // Output: US 104 | fmt.Println(info.CountryName) 105 | // Output: United States 106 | ``` 107 | 108 | ## European Union (EU) Country 109 | 110 | `info.IsEU` returns a boolean response to see if a country is a European Union country or not. 111 | 112 | ```go 113 | fmt.Println(info.IsEU) 114 | // Output: false 115 | ``` 116 | 117 | ## Country Flag 118 | 119 | Get country flag as an emoji and its Unicode value with `info.CountryFlag.Emoji` and `info.CountryFlag.Unicode` respectively. 120 | 121 | ```go 122 | fmt.Println(info.CountryFlag.Emoji) 123 | // Output: 🇳🇿 124 | fmt.Println(info.CountryFlag.Unicode) 125 | // Output: "U+1F1F3 U+1F1FF" 126 | ``` 127 | 128 | ## Country Flag URL 129 | 130 | Get the link of a country's flag image. 131 | 132 | ```go 133 | fmt.Println(info.CountryFlagURL) 134 | // Output: https://cdn.ipinfo.io/static/images/countries-flags/US.svg" 135 | ``` 136 | 137 | ## Country Currency 138 | 139 | Get country's currency code and its symbol with `info.CountryCurrency.Code` and `info.CountryCurrency.Symbol` respectively. 140 | 141 | ```go 142 | fmt.Println(info.CountryCurrency.Code) 143 | // Output: USD 144 | fmt.Println(info.CountryCurrency.Symbol) 145 | // Output: $ 146 | ``` 147 | 148 | ## Continent 149 | 150 | Get the IP's continent code and its name with `info.Continent.Code` and `info.Continent.Name` respectively. 151 | 152 | ```go 153 | fmt.Println(info.Continent.Code) 154 | // Output: NA 155 | fmt.Println(info.Continent.Name) 156 | // Output: North America 157 | ``` 158 | 159 | # Map IP Address 160 | 161 | You can map up to 500,000 IP addresses all at once using the `GetIPMap` command. You can input: 162 | 163 | - IP addresses (IPV4 and IPV6 both) 164 | - IP Ranges or Netblock 165 | - ASN 166 | 167 | After the operation, you will be presented with a URL to a map generated on the IPinfo website. 168 | 169 | IP Map Code: 170 | 171 | ```go 172 | package main 173 | 174 | import ( 175 | "fmt" 176 | "log" 177 | "net" 178 | 179 | "github.com/ipinfo/go/v2/ipinfo" 180 | ) 181 | 182 | func main() { 183 | client := ipinfo.NewClient(nil, nil, "YOUR_TOKEN") 184 | result, err := client.GetIPMap( 185 | []net.IP{ 186 | net.ParseIP("136.111.157.61"), 187 | net.ParseIP("231.163.78.134"), 188 | // ... 189 | net.ParseIP("228.128.213.179"), 190 | net.ParseIP("103.172.175.76"), 191 | }, 192 | ) 193 | if err != nil { 194 | log.Fatal(err) 195 | } 196 | 197 | fmt.Println(result) 198 | } 199 | 200 | ``` 201 | 202 | Result: 203 | 204 | See the output example map: https://ipinfo.io/tools/map/f27c7d40-3ff0-4ac2-878f-8d953dbcd3c8 205 | 206 | # Summarize IP Address 207 | 208 | Summarize IP addresses with `GetIPSummary` and output a report. 209 | 210 | ```go 211 | package main 212 | 213 | import ( 214 | "fmt" 215 | "log" 216 | "net" 217 | 218 | "github.com/ipinfo/go/v2/ipinfo" 219 | ) 220 | 221 | func main() { 222 | client := ipinfo.NewClient(nil, nil, "YOUR_TOKEN") 223 | result, err := client.GetIPSummary( 224 | []net.IP{ 225 | net.ParseIP("171.164.236.38"), 226 | net.ParseIP("206.132.224.214"), 227 | // .... 228 | net.ParseIP("208.191.89.104"), 229 | net.ParseIP("81.216.14.76"), 230 | }, 231 | ) 232 | if err != nil { 233 | log.Fatal(err) 234 | } 235 | 236 | fmt.Println(result) 237 | // Ouptut: {100 100 map[CN:7 DE:4 JP:12 MX:3 US:32] map[Columbus, ... 238 | 239 | } 240 | 241 | ``` 242 | 243 | # Batch Operations / Bulk Lookup 244 | 245 | You can do batch lookups or bulk lookups quite easily as well. The inputs supported: 246 | 247 | - IP addresses. IPV4 and IPV6 both 248 | - ASN 249 | - Specific field endpoint of an IP address e.g. `8.8.8.8/country` 250 | 251 | 252 | ```go 253 | package main 254 | 255 | import ( 256 | "fmt" 257 | "log" 258 | "time" 259 | "github.com/ipinfo/go/v2/ipinfo" 260 | "github.com/ipinfo/go/v2/ipinfo/cache" 261 | ) 262 | 263 | func main() { 264 | client := ipinfo.NewClient( 265 | nil, 266 | ipinfo.NewCache(cache.NewInMemory().WithExpiration(5*time.Minute)), 267 | "YOUR_TOKEN", 268 | ) 269 | 270 | // batchResult will contain all the batch lookup data 271 | batchResult, err := client.GetBatch( 272 | []string{ 273 | "104.193.114.182", // you can pass IPV4 address 274 | "8.8.8.8/country", // you can get specific information 275 | "AS36811", // you can lookup ASN details 276 | "2a03:2880:f10a:83:face:b00c:0:25de", // IPV6 address 277 | }, 278 | ipinfo.BatchReqOpts{ 279 | BatchSize: 2, 280 | TimeoutPerBatch: 0, 281 | TimeoutTotal: 5, 282 | }, 283 | ) 284 | if err != nil { 285 | log.Fatal(err) 286 | } 287 | for k, v := range batchResult { 288 | fmt.Printf("k=%v v=%v\n", k, v) 289 | } 290 | } 291 | ``` 292 | 293 | Examples of Batch / Bulk Lookup: 294 | 295 | - [Batch ASN](/example/batch-asn) 296 | - [Batch Core Net-IP](/example/batch-core-netip) 297 | - [Batch Core str](/example/batch-core-str) 298 | - [Batch Generic](/example/batch-generic) 299 | 300 | The loop declaration in the batch lookup showcases the "caching" capability of the IPinfo package. 301 | 302 | ### Lite API 303 | 304 | The library gives the possibility to use the [Lite API](https://ipinfo.io/developers/lite-api) too, authentication with your token is still required. 305 | 306 | The returned details are slightly different from the Core API. 307 | 308 | ```go 309 | package main 310 | 311 | import ( 312 | "fmt" 313 | "log" 314 | "net" 315 | "github.com/ipinfo/go/v2/ipinfo" 316 | ) 317 | 318 | func main() { 319 | const token = "YOUR_TOKEN" 320 | 321 | // Create a Lite client 322 | client := ipinfo.NewLiteClient(nil, nil, token) 323 | 324 | // Or use the package-level client 325 | ipinfo.SetLiteToken(token) 326 | 327 | info, err := ipinfo.GetIPInfoLite(net.ParseIP("8.8.8.8")) 328 | if err != nil { 329 | log.Fatal(err) 330 | } 331 | 332 | fmt.Println(info.ASN) // AS15169 333 | fmt.Println(info.Country) // United States 334 | fmt.Println(info.CountryCode) // US 335 | } 336 | ``` 337 | 338 | # Other Libraries 339 | 340 | There are official [IPinfo client libraries](https://ipinfo.io/developers/libraries) available for many languages including PHP, Python, Go, Java, Ruby, and many popular frameworks such as Django, Rails, and Laravel. There are also many third-party libraries and integrations available for our API. 341 | 342 | # About IPinfo 343 | 344 | Founded in 2013, IPinfo prides itself on being the most reliable, accurate, and in-depth source of IP address data available anywhere. We process terabytes of data to produce our custom IP geolocation, company, carrier, VPN detection, hosted domains, and IP type data sets. Our API handles over 40 billion requests a month for 100,000 businesses and developers. 345 | 346 | [![image](https://avatars3.githubusercontent.com/u/15721521?s=128&u=7bb7dde5c4991335fb234e68a30971944abc6bf3&v=4)](https://ipinfo.io/) 347 | -------------------------------------------------------------------------------- /ipinfo/batch.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/json" 7 | "fmt" 8 | "net" 9 | "strings" 10 | "sync" 11 | "time" 12 | 13 | "golang.org/x/sync/errgroup" 14 | ) 15 | 16 | const ( 17 | batchMaxSize = 1000 18 | batchReqTimeoutDefault = 5 19 | batchDefaultConcurrentRequestsLimit = 8 20 | ) 21 | 22 | // Internal batch type used by common batch functionality to temporarily store 23 | // the URL-to-result mapping in a half-decoded state (specifically the value 24 | // not being decoded yet). This allows us to decode the value to a proper 25 | // concrete type like `Core` or `ASNDetails` after analyzing the key to 26 | // determine which one it should be. 27 | type batch map[string]json.RawMessage 28 | 29 | // Batch is a mapped result of any valid API endpoint (e.g. ``, 30 | // `/`, ``, etc) to its corresponding data. 31 | // 32 | // The corresponding value will be either `*Core`, `*ASNDetails` or a generic 33 | // map for unknown value results. 34 | type Batch map[string]interface{} 35 | 36 | // BatchCore is a mapped result of IPs to their corresponding `Core` data. 37 | type BatchCore map[string]*Core 38 | 39 | // BatchASNDetails is a mapped result of ASNs to their corresponding 40 | // `ASNDetails` data. 41 | type BatchASNDetails map[string]*ASNDetails 42 | 43 | // BatchReqOpts are options input into batch request functions. 44 | type BatchReqOpts struct { 45 | // BatchSize is the internal batch size used per API request; the IPinfo 46 | // API has a maximum batch size, but the batch request functions available 47 | // in this library do not. Therefore the library chunks the input slices 48 | // internally into chunks of size `BatchSize`, clipping to the maximum 49 | // allowed by the IPinfo API. 50 | // 51 | // 0 means to use the default batch size which is the max allowed by the 52 | // IPinfo API. 53 | BatchSize uint32 54 | 55 | // TimeoutPerBatch is the timeout in seconds that each batch of size 56 | // `BatchSize` will have for its own request. 57 | // 58 | // 0 means to use a default of 5 seconds; any negative number will turn it 59 | // off; turning it off does _not_ disable the effects of `TimeoutTotal`. 60 | TimeoutPerBatch int64 61 | 62 | // TimeoutTotal is the total timeout in seconds for all batch requests in a 63 | // batch request function to complete. 64 | // 65 | // 0 means no total timeout; `TimeoutPerBatch` will still apply. 66 | TimeoutTotal uint64 67 | 68 | // ConcurrentBatchRequestsLimit is the maximum number of concurrent batch 69 | // requests that will be mid-flight for inputs that exceed the batch limit. 70 | // 71 | // 0 means to use a default of 8; any negative number implies unlimited concurrency. 72 | ConcurrentBatchRequestsLimit int 73 | 74 | // Filter, if turned on, will filter out a URL whose value was deemed empty 75 | // on the server. 76 | Filter bool 77 | } 78 | 79 | /* GENERIC */ 80 | 81 | // GetBatch does a batch request for all `urls` at once. 82 | func GetBatch( 83 | urls []string, 84 | opts BatchReqOpts, 85 | ) (Batch, error) { 86 | return DefaultClient.GetBatch(urls, opts) 87 | } 88 | 89 | // GetBatch does a batch request for all `urls` at once. 90 | func (c *Client) GetBatch( 91 | urls []string, 92 | opts BatchReqOpts, 93 | ) (Batch, error) { 94 | var batchSize int 95 | var timeoutPerBatch int64 96 | var maxConcurrentBatchRequests int 97 | var totalTimeoutCtx context.Context 98 | var totalTimeoutCancel context.CancelFunc 99 | var lookupUrls []string 100 | var result Batch 101 | var mu sync.Mutex 102 | 103 | // if the cache is available, filter out URLs already cached. 104 | result = make(Batch, len(urls)) 105 | if c.Cache != nil { 106 | lookupUrls = make([]string, 0, len(urls)/2) 107 | for _, url := range urls { 108 | if res, err := c.Cache.Get(cacheKey(url)); err == nil { 109 | result[url] = res 110 | } else { 111 | lookupUrls = append(lookupUrls, url) 112 | } 113 | } 114 | } else { 115 | lookupUrls = urls 116 | } 117 | 118 | // everything cached; exit early. 119 | if len(lookupUrls) == 0 { 120 | return result, nil 121 | } 122 | 123 | // use correct batch size; default/clip to `batchMaxSize`. 124 | if opts.BatchSize == 0 || opts.BatchSize > batchMaxSize { 125 | batchSize = batchMaxSize 126 | } else { 127 | batchSize = int(opts.BatchSize) 128 | } 129 | 130 | // use correct concurrent requests limit; either default or user-provided. 131 | if opts.ConcurrentBatchRequestsLimit == 0 { 132 | maxConcurrentBatchRequests = batchDefaultConcurrentRequestsLimit 133 | } else { 134 | maxConcurrentBatchRequests = opts.ConcurrentBatchRequestsLimit 135 | } 136 | 137 | // use correct timeout per batch; either default or user-provided. 138 | if opts.TimeoutPerBatch == 0 { 139 | timeoutPerBatch = batchReqTimeoutDefault 140 | } else { 141 | timeoutPerBatch = opts.TimeoutPerBatch 142 | } 143 | 144 | // use correct timeout total; either ignore it or apply user-provided. 145 | if opts.TimeoutTotal > 0 { 146 | totalTimeoutCtx, totalTimeoutCancel = context.WithTimeout( 147 | context.Background(), 148 | time.Duration(opts.TimeoutTotal)*time.Second, 149 | ) 150 | defer totalTimeoutCancel() 151 | } else { 152 | totalTimeoutCtx = context.Background() 153 | } 154 | 155 | errg, ctx := errgroup.WithContext(totalTimeoutCtx) 156 | errg.SetLimit(maxConcurrentBatchRequests) 157 | for i := 0; i < len(lookupUrls); i += batchSize { 158 | end := i + batchSize 159 | if end > len(lookupUrls) { 160 | end = len(lookupUrls) 161 | } 162 | 163 | urlsChunk := lookupUrls[i:end] 164 | errg.Go(func() error { 165 | var postURL string 166 | 167 | // prepare request. 168 | 169 | var timeoutPerBatchCtx context.Context 170 | var timeoutPerBatchCancel context.CancelFunc 171 | if timeoutPerBatch > 0 { 172 | timeoutPerBatchCtx, timeoutPerBatchCancel = context.WithTimeout( 173 | ctx, 174 | time.Duration(timeoutPerBatch)*time.Second, 175 | ) 176 | defer timeoutPerBatchCancel() 177 | } else { 178 | timeoutPerBatchCtx = context.Background() 179 | } 180 | 181 | if opts.Filter { 182 | postURL = "batch?filter=1" 183 | } else { 184 | postURL = "batch" 185 | } 186 | 187 | jsonArrStr, err := json.Marshal(urlsChunk) 188 | if err != nil { 189 | return err 190 | } 191 | jsonBuf := bytes.NewBuffer(jsonArrStr) 192 | 193 | req, err := c.newRequest(timeoutPerBatchCtx, "POST", postURL, jsonBuf) 194 | if err != nil { 195 | return err 196 | } 197 | req.Header.Set("Content-Type", "application/json") 198 | 199 | // temporarily make a new local result map so that we can read the 200 | // network data into it; once we have it local we'll merge it with 201 | // `result` in a concurrency-safe way. 202 | localResult := new(batch) 203 | if _, err := c.do(req, localResult); err != nil { 204 | return err 205 | } 206 | 207 | // update final result. 208 | mu.Lock() 209 | defer mu.Unlock() 210 | for k, v := range *localResult { 211 | if strings.HasPrefix(k, "AS") { 212 | decodedV := new(ASNDetails) 213 | if err := json.Unmarshal(v, decodedV); err != nil { 214 | return err 215 | } 216 | 217 | decodedV.setCountryName() 218 | result[k] = decodedV 219 | } else if net.ParseIP(k) != nil { 220 | decodedV := new(Core) 221 | if err := json.Unmarshal(v, decodedV); err != nil { 222 | return err 223 | } 224 | 225 | decodedV.setCountryName() 226 | result[k] = decodedV 227 | } else { 228 | decodedV := new(interface{}) 229 | if err := json.Unmarshal(v, decodedV); err != nil { 230 | return err 231 | } 232 | 233 | result[k] = decodedV 234 | } 235 | } 236 | 237 | return nil 238 | }) 239 | } 240 | if err := errg.Wait(); err != nil { 241 | return result, err 242 | } 243 | 244 | // we delay inserting into the cache until now because: 245 | // 1. it's likely more cache-line friendly. 246 | // 2. doing it while updating `result` inside the request workers would be 247 | // problematic if the cache is external since we take a mutex lock for 248 | // that entire period. 249 | if c.Cache != nil { 250 | for _, url := range lookupUrls { 251 | if v, exists := result[url]; exists { 252 | if err := c.Cache.Set(cacheKey(url), v); err != nil { 253 | // NOTE: still return the result even if the cache fails. 254 | return result, err 255 | } 256 | } 257 | } 258 | } 259 | 260 | return result, nil 261 | } 262 | 263 | /* CORE (net.IP) */ 264 | 265 | // GetIPInfoBatch does a batch request for all `ips` at once. 266 | func GetIPInfoBatch( 267 | ips []net.IP, 268 | opts BatchReqOpts, 269 | ) (BatchCore, error) { 270 | return DefaultClient.GetIPInfoBatch(ips, opts) 271 | } 272 | 273 | // GetIPInfoBatch does a batch request for all `ips` at once. 274 | func (c *Client) GetIPInfoBatch( 275 | ips []net.IP, 276 | opts BatchReqOpts, 277 | ) (BatchCore, error) { 278 | ipstrs := make([]string, 0, len(ips)) 279 | if c.Token == "" { 280 | return nil, fmt.Errorf("invalid token") 281 | } 282 | for _, ip := range ips { 283 | if ip == nil { 284 | continue 285 | } 286 | ipstrs = append(ipstrs, ip.String()) 287 | } 288 | 289 | return c.GetIPStrInfoBatch(ipstrs, opts) 290 | } 291 | 292 | /* CORE (string) */ 293 | 294 | // GetIPStrInfoBatch does a batch request for all `ips` at once. 295 | func GetIPStrInfoBatch( 296 | ips []string, 297 | opts BatchReqOpts, 298 | ) (BatchCore, error) { 299 | return DefaultClient.GetIPStrInfoBatch(ips, opts) 300 | } 301 | 302 | // GetIPStrInfoBatch does a batch request for all `ips` at once. 303 | func (c *Client) GetIPStrInfoBatch( 304 | ips []string, 305 | opts BatchReqOpts, 306 | ) (BatchCore, error) { 307 | intermediateRes, err := c.GetBatch(ips, opts) 308 | 309 | // if we have items in the result, don't throw them away; we'll convert 310 | // below and return the error together if it existed. 311 | if err != nil && len(intermediateRes) == 0 { 312 | return nil, err 313 | } 314 | 315 | res := make(BatchCore, len(intermediateRes)) 316 | for k, v := range intermediateRes { 317 | res[k] = v.(*Core) 318 | } 319 | 320 | return res, err 321 | } 322 | 323 | /* ASN */ 324 | 325 | // GetASNDetailsBatch does a batch request for all `asns` at once. 326 | func GetASNDetailsBatch( 327 | asns []string, 328 | opts BatchReqOpts, 329 | ) (BatchASNDetails, error) { 330 | return DefaultClient.GetASNDetailsBatch(asns, opts) 331 | } 332 | 333 | // GetASNDetailsBatch does a batch request for all `asns` at once. 334 | func (c *Client) GetASNDetailsBatch( 335 | asns []string, 336 | opts BatchReqOpts, 337 | ) (BatchASNDetails, error) { 338 | intermediateRes, err := c.GetBatch(asns, opts) 339 | 340 | // if we have items in the result, don't throw them away; we'll convert 341 | // below and return the error together if it existed. 342 | if err != nil && len(intermediateRes) == 0 { 343 | return nil, err 344 | } 345 | 346 | res := make(BatchASNDetails, len(intermediateRes)) 347 | for k, v := range intermediateRes { 348 | res[k] = v.(*ASNDetails) 349 | } 350 | return res, err 351 | } 352 | -------------------------------------------------------------------------------- /ipinfo/core.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | import ( 4 | "net" 5 | "net/http" 6 | "net/netip" 7 | ) 8 | 9 | // Core represents data from the Core API. 10 | type Core struct { 11 | IP net.IP `json:"ip" csv:"ip"` 12 | Hostname string `json:"hostname,omitempty" csv:"hostname" yaml:"hostname,omitempty"` 13 | Bogon bool `json:"bogon,omitempty" csv:"bogon" yaml:"bogon,omitempty"` 14 | Anycast bool `json:"anycast,omitempty" csv:"anycast" yaml:"anycast,omitempty"` 15 | City string `json:"city,omitempty" csv:"city" yaml:"city,omitempty"` 16 | Region string `json:"region,omitempty" csv:"region" yaml:"region,omitempty"` 17 | Country string `json:"country,omitempty" csv:"country" yaml:"country,omitempty"` 18 | CountryName string `json:"country_name,omitempty" csv:"country_name" yaml:"countryName,omitempty"` 19 | CountryFlag CountryFlag `json:"country_flag,omitempty" csv:"country_flag_,inline" yaml:"countryFlag,omitempty"` 20 | CountryFlagURL string `json:"country_flag_url,omitempty" csv:"country_flag_url" yaml:"countryFlagURL,omitempty"` 21 | CountryCurrency CountryCurrency `json:"country_currency,omitempty" csv:"country_currency_,inline" yaml:"countryCurrency,omitempty"` 22 | Continent Continent `json:"continent,omitempty" csv:"continent_,inline" yaml:"continent,omitempty"` 23 | IsEU bool `json:"isEU,omitempty" csv:"isEU" yaml:"isEU,omitempty"` 24 | Location string `json:"loc,omitempty" csv:"loc" yaml:"location,omitempty"` 25 | Org string `json:"org,omitempty" csv:"org" yaml:"org,omitempty"` 26 | Postal string `json:"postal,omitempty" csv:"postal" yaml:"postal,omitempty"` 27 | Timezone string `json:"timezone,omitempty" csv:"timezone" yaml:"timezone,omitempty"` 28 | ASN *CoreASN `json:"asn,omitempty" csv:"asn_,inline" yaml:"asn,omitempty"` 29 | Company *CoreCompany `json:"company,omitempty" csv:"company_,inline" yaml:"company,omitempty"` 30 | Carrier *CoreCarrier `json:"carrier,omitempty" csv:"carrier_,inline" yaml:"carrier,omitempty"` 31 | Privacy *CorePrivacy `json:"privacy,omitempty" csv:"privacy_,inline" yaml:"privacy,omitempty"` 32 | Abuse *CoreAbuse `json:"abuse,omitempty" csv:"abuse_,inline" yaml:"abuse,omitempty"` 33 | Domains *CoreDomains `json:"domains,omitempty" csv:"domains_,inline" yaml:"domains,omitempty"` 34 | } 35 | 36 | // CoreASN represents ASN data for the Core API. 37 | type CoreASN struct { 38 | ASN string `json:"asn" csv:"id"` 39 | Name string `json:"name" csv:"asn"` 40 | Domain string `json:"domain" csv:"domain"` 41 | Route string `json:"route" csv:"route"` 42 | Type string `json:"type" csv:"type"` 43 | } 44 | 45 | // CoreCompany represents company data for the Core API. 46 | type CoreCompany struct { 47 | Name string `json:"name" csv:"name"` 48 | Domain string `json:"domain" csv:"domain"` 49 | Type string `json:"type" csv:"type"` 50 | } 51 | 52 | // CoreCarrier represents carrier data for the Core API. 53 | type CoreCarrier struct { 54 | Name string `json:"name" csv:"name"` 55 | MCC string `json:"mcc" csv:"mcc"` 56 | MNC string `json:"mnc" csv:"mnc"` 57 | } 58 | 59 | // CorePrivacy represents privacy data for the Core API. 60 | type CorePrivacy struct { 61 | VPN bool `json:"vpn" csv:"vpn"` 62 | Proxy bool `json:"proxy" csv:"proxy"` 63 | Tor bool `json:"tor" csv:"tor"` 64 | Relay bool `json:"relay" csv:"relay"` 65 | Hosting bool `json:"hosting" csv:"hosting"` 66 | Service string `json:"service" csv:"service"` 67 | } 68 | 69 | // CoreAbuse represents abuse data for the Core API. 70 | type CoreAbuse struct { 71 | Address string `json:"address" csv:"address"` 72 | Country string `json:"country" csv:"country"` 73 | CountryName string `json:"country_name" csv:"country_name"` 74 | Email string `json:"email" csv:"email"` 75 | Name string `json:"name" csv:"name"` 76 | Network string `json:"network" csv:"network"` 77 | Phone string `json:"phone" csv:"phone"` 78 | } 79 | 80 | // CoreDomains represents domains data for the Core API. 81 | type CoreDomains struct { 82 | IP string `json:"ip" csv:"-"` 83 | Total uint64 `json:"total" csv:"total"` 84 | Domains []string `json:"domains" csv:"-"` 85 | } 86 | 87 | func (v *Core) setCountryName() { 88 | if v.Country != "" { 89 | v.CountryName = GetCountryName(v.Country) 90 | v.IsEU = IsEU(v.Country) 91 | v.CountryFlag.Emoji = GetCountryFlagEmoji(v.Country) 92 | v.CountryFlag.Unicode = GetCountryFlagUnicode(v.Country) 93 | v.CountryFlagURL = GetCountryFlagURL(v.Country) 94 | v.CountryCurrency.Code = GetCountryCurrencyCode(v.Country) 95 | v.CountryCurrency.Symbol = GetCountryCurrencySymbol(v.Country) 96 | v.Continent.Code = GetContinentCode(v.Country) 97 | v.Continent.Name = GetContinentName(v.Country) 98 | } 99 | if v.Abuse != nil && v.Abuse.Country != "" { 100 | v.Abuse.CountryName = GetCountryName(v.Abuse.Country) 101 | } 102 | } 103 | 104 | /* CORE */ 105 | 106 | // GetIPInfo returns the details for the specified IP. 107 | func GetIPInfo(ip net.IP) (*Core, error) { 108 | return DefaultClient.GetIPInfo(ip) 109 | } 110 | 111 | // GetIPInfoV6 returns the details for the specified IPv6 IP. 112 | func GetIPInfoV6(ip net.IP) (*Core, error) { 113 | return DefaultClient.GetIPInfoV6(ip) 114 | } 115 | 116 | // GetIPInfo returns the details for the specified IP. 117 | func (c *Client) GetIPInfo(ip net.IP) (*Core, error) { 118 | return c.getIPInfoBase(ip, false) 119 | } 120 | 121 | // GetIPInfoV6 returns the details for the specified IPv6 IP. 122 | func (c *Client) GetIPInfoV6(ip net.IP) (*Core, error) { 123 | return c.getIPInfoBase(ip, true) 124 | } 125 | 126 | func (c *Client) getIPInfoBase(ip net.IP, ipv6 bool) (*Core, error) { 127 | relURL := "" 128 | if ip != nil && isBogon(netip.MustParseAddr(ip.String())) { 129 | bogonResponse := new(Core) 130 | bogonResponse.Bogon = true 131 | bogonResponse.IP = ip 132 | return bogonResponse, nil 133 | } 134 | if ip != nil { 135 | relURL = ip.String() 136 | } 137 | 138 | // perform cache lookup. 139 | if c.Cache != nil { 140 | if res, err := c.Cache.Get(cacheKey(relURL)); err == nil { 141 | return res.(*Core), nil 142 | } 143 | } 144 | 145 | // prepare req 146 | var err error 147 | var req *http.Request 148 | if ipv6 { 149 | req, err = c.newRequestV6(nil, "GET", relURL, nil) 150 | } else { 151 | req, err = c.newRequest(nil, "GET", relURL, nil) 152 | } 153 | if err != nil { 154 | return nil, err 155 | } 156 | 157 | // do req 158 | v := new(Core) 159 | if _, err := c.do(req, v); err != nil { 160 | return nil, err 161 | } 162 | 163 | // format 164 | v.setCountryName() 165 | 166 | // cache req result 167 | if c.Cache != nil { 168 | if err := c.Cache.Set(cacheKey(relURL), v); err != nil { 169 | // NOTE: still return the value even if the cache fails. 170 | return v, err 171 | } 172 | } 173 | 174 | return v, nil 175 | } 176 | 177 | /* IP ADDRESS */ 178 | 179 | // GetIPAddr returns the IP address that IPinfo sees when you make a request. 180 | func GetIPAddr() (string, error) { 181 | return DefaultClient.GetIPAddr() 182 | } 183 | 184 | // GetIPAddr returns the IP address that IPinfo sees when you make a request. 185 | func (c *Client) GetIPAddr() (string, error) { 186 | core, err := c.GetIPInfo(nil) 187 | if err != nil { 188 | return "", err 189 | } 190 | return core.IP.String(), nil 191 | } 192 | 193 | /* HOSTNAME */ 194 | 195 | // GetIPHostname returns the hostname of the domain on the specified IP. 196 | func GetIPHostname(ip net.IP) (string, error) { 197 | return DefaultClient.GetIPHostname(ip) 198 | } 199 | 200 | // GetIPHostname returns the hostname of the domain on the specified IP. 201 | func (c *Client) GetIPHostname(ip net.IP) (string, error) { 202 | core, err := c.GetIPInfo(ip) 203 | if err != nil { 204 | return "", err 205 | } 206 | return core.Hostname, nil 207 | } 208 | 209 | /* BOGON */ 210 | 211 | // GetIPBogon returns whether an IP is a bogon IP. 212 | func GetIPBogon(ip net.IP) (bool, error) { 213 | return DefaultClient.GetIPBogon(ip) 214 | } 215 | 216 | // GetIPBogon returns whether an IP is a bogon IP. 217 | func (c *Client) GetIPBogon(ip net.IP) (bool, error) { 218 | core, err := c.GetIPInfo(ip) 219 | if err != nil { 220 | return false, err 221 | } 222 | return core.Bogon, nil 223 | } 224 | 225 | /* ANYCAST */ 226 | 227 | // GetIPAnycast returns whether an IP is an anycast IP. 228 | func GetIPAnycast(ip net.IP) (bool, error) { 229 | return DefaultClient.GetIPAnycast(ip) 230 | } 231 | 232 | // GetIPAnycast returns whether an IP is an anycast IP. 233 | func (c *Client) GetIPAnycast(ip net.IP) (bool, error) { 234 | core, err := c.GetIPInfo(ip) 235 | if err != nil { 236 | return false, err 237 | } 238 | return core.Anycast, nil 239 | } 240 | 241 | /* CITY */ 242 | 243 | // GetIPCity returns the city for the specified IP. 244 | func GetIPCity(ip net.IP) (string, error) { 245 | return DefaultClient.GetIPCity(ip) 246 | } 247 | 248 | // GetIPCity returns the city for the specified IP. 249 | func (c *Client) GetIPCity(ip net.IP) (string, error) { 250 | core, err := c.GetIPInfo(ip) 251 | if err != nil { 252 | return "", err 253 | } 254 | return core.City, nil 255 | } 256 | 257 | /* REGION */ 258 | 259 | // GetIPRegion returns the region for the specified IP. 260 | func GetIPRegion(ip net.IP) (string, error) { 261 | return DefaultClient.GetIPRegion(ip) 262 | } 263 | 264 | // GetIPRegion returns the region for the specified IP. 265 | func (c *Client) GetIPRegion(ip net.IP) (string, error) { 266 | core, err := c.GetIPInfo(ip) 267 | if err != nil { 268 | return "", err 269 | } 270 | return core.Region, nil 271 | } 272 | 273 | /* COUNTRY */ 274 | 275 | // GetIPCountry returns the country for the specified IP. 276 | func GetIPCountry(ip net.IP) (string, error) { 277 | return DefaultClient.GetIPCountry(ip) 278 | } 279 | 280 | // GetIPCountry returns the country for the specified IP. 281 | func (c *Client) GetIPCountry(ip net.IP) (string, error) { 282 | core, err := c.GetIPInfo(ip) 283 | if err != nil { 284 | return "", err 285 | } 286 | return core.Country, nil 287 | } 288 | 289 | /* COUNTRY NAME */ 290 | 291 | // GetIPCountryName returns the full country name for the specified IP. 292 | func GetIPCountryName(ip net.IP) (string, error) { 293 | return DefaultClient.GetIPCountryName(ip) 294 | } 295 | 296 | // GetIPCountryName returns the full country name for the specified IP. 297 | func (c *Client) GetIPCountryName(ip net.IP) (string, error) { 298 | core, err := c.GetIPInfo(ip) 299 | if err != nil { 300 | return "", err 301 | } 302 | return core.CountryName, nil 303 | } 304 | 305 | /* LOCATION */ 306 | 307 | // GetIPLocation returns the location for the specified IP. 308 | func GetIPLocation(ip net.IP) (string, error) { 309 | return DefaultClient.GetIPLocation(ip) 310 | } 311 | 312 | // GetIPLocation returns the location for the specified IP. 313 | func (c *Client) GetIPLocation(ip net.IP) (string, error) { 314 | core, err := c.GetIPInfo(ip) 315 | if err != nil { 316 | return "", err 317 | } 318 | return core.Location, nil 319 | } 320 | 321 | /* ORG */ 322 | 323 | // GetIPOrg returns the organization for the specified IP. 324 | func GetIPOrg(ip net.IP) (string, error) { 325 | return DefaultClient.GetIPOrg(ip) 326 | } 327 | 328 | // GetIPOrg returns the organization for the specified IP. 329 | func (c *Client) GetIPOrg(ip net.IP) (string, error) { 330 | core, err := c.GetIPInfo(ip) 331 | if err != nil { 332 | return "", err 333 | } 334 | return core.Org, nil 335 | } 336 | 337 | /* POSTAL */ 338 | 339 | // GetIPPostal returns the postal for the specified IP. 340 | func GetIPPostal(ip net.IP) (string, error) { 341 | return DefaultClient.GetIPPostal(ip) 342 | } 343 | 344 | // GetIPPostal returns the postal for the specified IP. 345 | func (c *Client) GetIPPostal(ip net.IP) (string, error) { 346 | core, err := c.GetIPInfo(ip) 347 | if err != nil { 348 | return "", err 349 | } 350 | return core.Postal, nil 351 | } 352 | 353 | /* TIMEZONE */ 354 | 355 | // GetIPTimezone returns the timezone for the specified IP. 356 | func GetIPTimezone(ip net.IP) (string, error) { 357 | return DefaultClient.GetIPTimezone(ip) 358 | } 359 | 360 | // GetIPTimezone returns the timezone for the specified IP. 361 | func (c *Client) GetIPTimezone(ip net.IP) (string, error) { 362 | core, err := c.GetIPInfo(ip) 363 | if err != nil { 364 | return "", err 365 | } 366 | return core.Timezone, nil 367 | } 368 | 369 | /* ASN */ 370 | 371 | // GetIPASN returns the ASN details for the specified IP. 372 | func GetIPASN(ip net.IP) (*CoreASN, error) { 373 | return DefaultClient.GetIPASN(ip) 374 | } 375 | 376 | // GetIPASN returns the ASN details for the specified IP. 377 | func (c *Client) GetIPASN(ip net.IP) (*CoreASN, error) { 378 | core, err := c.GetIPInfo(ip) 379 | if err != nil { 380 | return nil, err 381 | } 382 | return core.ASN, nil 383 | } 384 | 385 | /* COMPANY */ 386 | 387 | // GetIPCompany returns the company details for the specified IP. 388 | func GetIPCompany(ip net.IP) (*CoreCompany, error) { 389 | return DefaultClient.GetIPCompany(ip) 390 | } 391 | 392 | // GetIPCompany returns the company details for the specified IP. 393 | func (c *Client) GetIPCompany(ip net.IP) (*CoreCompany, error) { 394 | core, err := c.GetIPInfo(ip) 395 | if err != nil { 396 | return nil, err 397 | } 398 | return core.Company, nil 399 | } 400 | 401 | /* CARRIER */ 402 | 403 | // GetIPCarrier returns the carrier details for the specified IP. 404 | func GetIPCarrier(ip net.IP) (*CoreCarrier, error) { 405 | return DefaultClient.GetIPCarrier(ip) 406 | } 407 | 408 | // GetIPCarrier returns the carrier details for the specified IP. 409 | func (c *Client) GetIPCarrier(ip net.IP) (*CoreCarrier, error) { 410 | core, err := c.GetIPInfo(ip) 411 | if err != nil { 412 | return nil, err 413 | } 414 | return core.Carrier, nil 415 | } 416 | 417 | /* PRIVACY */ 418 | 419 | // GetIPPrivacy returns the privacy details for the specified IP. 420 | func GetIPPrivacy(ip net.IP) (*CorePrivacy, error) { 421 | return DefaultClient.GetIPPrivacy(ip) 422 | } 423 | 424 | // GetIPPrivacy returns the privacy details for the specified IP. 425 | func (c *Client) GetIPPrivacy(ip net.IP) (*CorePrivacy, error) { 426 | core, err := c.GetIPInfo(ip) 427 | if err != nil { 428 | return nil, err 429 | } 430 | return core.Privacy, nil 431 | } 432 | 433 | /* ABUSE */ 434 | 435 | // GetIPAbuse returns the abuse details for the specified IP. 436 | func GetIPAbuse(ip net.IP) (*CoreAbuse, error) { 437 | return DefaultClient.GetIPAbuse(ip) 438 | } 439 | 440 | // GetIPAbuse returns the abuse details for the specified IP. 441 | func (c *Client) GetIPAbuse(ip net.IP) (*CoreAbuse, error) { 442 | core, err := c.GetIPInfo(ip) 443 | if err != nil { 444 | return nil, err 445 | } 446 | return core.Abuse, nil 447 | } 448 | 449 | /* DOMAINS */ 450 | 451 | // GetIPDomains returns the domains details for the specified IP. 452 | func GetIPDomains(ip net.IP) (*CoreDomains, error) { 453 | return DefaultClient.GetIPDomains(ip) 454 | } 455 | 456 | // GetIPDomains returns the domains details for the specified IP. 457 | func (c *Client) GetIPDomains(ip net.IP) (*CoreDomains, error) { 458 | core, err := c.GetIPInfo(ip) 459 | if err != nil { 460 | return nil, err 461 | } 462 | return core.Domains, nil 463 | } 464 | -------------------------------------------------------------------------------- /ipinfo/countries.go: -------------------------------------------------------------------------------- 1 | package ipinfo 2 | 3 | const ( 4 | countryFlagsBaseURL = "https://cdn.ipinfo.io/static/images/countries-flags/" 5 | ) 6 | 7 | // GetCountryName gets the full name of a country from its code, e.g. 8 | // "PK" -> "Pakistan". 9 | func GetCountryName(country string) string { 10 | return countriesMap[country] 11 | } 12 | 13 | // GetCountryFlagEmoji gets the emoji flag of a country from its code, e.g. 14 | // "PK" -> "🇵🇰". 15 | func GetCountryFlagEmoji(country string) string { 16 | return countriesFlags[country].Emoji 17 | } 18 | 19 | // GetCountryFlagUnicode gets the unicode of an emoji from country code, e.g. 20 | // "PK" -> "U+1F1F5 U+1F1F0". 21 | func GetCountryFlagUnicode(country string) string { 22 | return countriesFlags[country].Unicode 23 | } 24 | 25 | // GetCountryCurrencyCode gets the currency code of a country from its code, e.g. 26 | // "PK" -> "PKR". 27 | func GetCountryCurrencyCode(country string) string { 28 | return countriesCurrencies[country].Code 29 | } 30 | 31 | // GetCountryCurrencySymbol gets the symbol of currency from country code, e.g. 32 | // "PK" -> "₨". 33 | func GetCountryCurrencySymbol(country string) string { 34 | return countriesCurrencies[country].Symbol 35 | } 36 | 37 | // GetContinentCode gets the continent code of a country from its code, e.g. 38 | // "PK" -> "AS". 39 | func GetContinentCode(country string) string { 40 | return continents[country].Code 41 | } 42 | 43 | // GetContinentName gets the name of continent from country code, e.g. 44 | // "PK" -> "Asia". 45 | func GetContinentName(country string) string { 46 | return continents[country].Name 47 | } 48 | 49 | // GetCountryFlagURL gets the URL of the country flag, e.g. 50 | // "PK" -> "https://cdn.ipinfo.io/static/images/countries-flags/PK.svg". 51 | func GetCountryFlagURL(country string) string { 52 | return countryFlagsBaseURL + country + ".svg" 53 | } 54 | 55 | // IsEU takes the country code and returns `true` 56 | // if the country is a member of the EU, e.g. "SE" -> true 57 | func IsEU(country string) bool { 58 | for _, val := range euCountries { 59 | if val == country { 60 | return true 61 | } 62 | } 63 | return false 64 | } 65 | 66 | type CountryFlag struct { 67 | Emoji string `json:"emoji,omitempty" csv:"emoji"` 68 | Unicode string `json:"unicode,omitempty" csv:"unicode"` 69 | } 70 | 71 | type CountryCurrency struct { 72 | Code string `json:"code,omitempty" csv:"code"` 73 | Symbol string `json:"symbol,omitempty" csv:"symbol"` 74 | } 75 | 76 | type Continent struct { 77 | Code string `json:"code,omitempty" csv:"code"` 78 | Name string `json:"name,omitempty" csv:"name"` 79 | } 80 | 81 | var countriesMap = map[string]string{ 82 | "BD": "Bangladesh", 83 | "BE": "Belgium", 84 | "BF": "Burkina Faso", 85 | "BG": "Bulgaria", 86 | "BA": "Bosnia and Herzegovina", 87 | "BB": "Barbados", 88 | "WF": "Wallis and Futuna", 89 | "BL": "Saint Barthelemy", 90 | "BM": "Bermuda", 91 | "BN": "Brunei", 92 | "BO": "Bolivia", 93 | "BH": "Bahrain", 94 | "BI": "Burundi", 95 | "BJ": "Benin", 96 | "BT": "Bhutan", 97 | "JM": "Jamaica", 98 | "BV": "Bouvet Island", 99 | "BW": "Botswana", 100 | "WS": "Samoa", 101 | "BQ": "Bonaire, Saint Eustatius and Saba ", 102 | "BR": "Brazil", 103 | "BS": "Bahamas", 104 | "JE": "Jersey", 105 | "BY": "Belarus", 106 | "BZ": "Belize", 107 | "RU": "Russia", 108 | "RW": "Rwanda", 109 | "RS": "Serbia", 110 | "TL": "East Timor", 111 | "RE": "Reunion", 112 | "TM": "Turkmenistan", 113 | "TJ": "Tajikistan", 114 | "RO": "Romania", 115 | "TK": "Tokelau", 116 | "GW": "Guinea-Bissau", 117 | "GU": "Guam", 118 | "GT": "Guatemala", 119 | "GS": "South Georgia and the South Sandwich Islands", 120 | "GR": "Greece", 121 | "GQ": "Equatorial Guinea", 122 | "GP": "Guadeloupe", 123 | "JP": "Japan", 124 | "GY": "Guyana", 125 | "GG": "Guernsey", 126 | "GF": "French Guiana", 127 | "GE": "Georgia", 128 | "GD": "Grenada", 129 | "GB": "United Kingdom", 130 | "GA": "Gabon", 131 | "SV": "El Salvador", 132 | "GN": "Guinea", 133 | "GM": "Gambia", 134 | "GL": "Greenland", 135 | "GI": "Gibraltar", 136 | "GH": "Ghana", 137 | "OM": "Oman", 138 | "TN": "Tunisia", 139 | "JO": "Jordan", 140 | "HR": "Croatia", 141 | "HT": "Haiti", 142 | "HU": "Hungary", 143 | "HK": "Hong Kong", 144 | "HN": "Honduras", 145 | "HM": "Heard Island and McDonald Islands", 146 | "VE": "Venezuela", 147 | "PR": "Puerto Rico", 148 | "PS": "Palestinian Territory", 149 | "PW": "Palau", 150 | "PT": "Portugal", 151 | "SJ": "Svalbard and Jan Mayen", 152 | "PY": "Paraguay", 153 | "IQ": "Iraq", 154 | "PA": "Panama", 155 | "PF": "French Polynesia", 156 | "PG": "Papua New Guinea", 157 | "PE": "Peru", 158 | "PK": "Pakistan", 159 | "PH": "Philippines", 160 | "PN": "Pitcairn", 161 | "PL": "Poland", 162 | "PM": "Saint Pierre and Miquelon", 163 | "ZM": "Zambia", 164 | "EH": "Western Sahara", 165 | "EE": "Estonia", 166 | "EG": "Egypt", 167 | "ZA": "South Africa", 168 | "EC": "Ecuador", 169 | "IT": "Italy", 170 | "VN": "Vietnam", 171 | "SB": "Solomon Islands", 172 | "ET": "Ethiopia", 173 | "SO": "Somalia", 174 | "ZW": "Zimbabwe", 175 | "SA": "Saudi Arabia", 176 | "ES": "Spain", 177 | "ER": "Eritrea", 178 | "ME": "Montenegro", 179 | "MD": "Moldova", 180 | "MG": "Madagascar", 181 | "MF": "Saint Martin", 182 | "MA": "Morocco", 183 | "MC": "Monaco", 184 | "UZ": "Uzbekistan", 185 | "MM": "Myanmar", 186 | "ML": "Mali", 187 | "MO": "Macao", 188 | "MN": "Mongolia", 189 | "MH": "Marshall Islands", 190 | "MK": "Macedonia", 191 | "MU": "Mauritius", 192 | "MT": "Malta", 193 | "MW": "Malawi", 194 | "MV": "Maldives", 195 | "MQ": "Martinique", 196 | "MP": "Northern Mariana Islands", 197 | "MS": "Montserrat", 198 | "MR": "Mauritania", 199 | "IM": "Isle of Man", 200 | "UG": "Uganda", 201 | "TZ": "Tanzania", 202 | "MY": "Malaysia", 203 | "MX": "Mexico", 204 | "IL": "Israel", 205 | "FR": "France", 206 | "IO": "British Indian Ocean Territory", 207 | "SH": "Saint Helena", 208 | "FI": "Finland", 209 | "FJ": "Fiji", 210 | "FK": "Falkland Islands", 211 | "FM": "Micronesia", 212 | "FO": "Faroe Islands", 213 | "NI": "Nicaragua", 214 | "NL": "Netherlands", 215 | "NO": "Norway", 216 | "NA": "Namibia", 217 | "VU": "Vanuatu", 218 | "NC": "New Caledonia", 219 | "NE": "Niger", 220 | "NF": "Norfolk Island", 221 | "NG": "Nigeria", 222 | "NZ": "New Zealand", 223 | "NP": "Nepal", 224 | "NR": "Nauru", 225 | "NU": "Niue", 226 | "CK": "Cook Islands", 227 | "XK": "Kosovo", 228 | "CI": "Ivory Coast", 229 | "CH": "Switzerland", 230 | "CO": "Colombia", 231 | "CN": "China", 232 | "CM": "Cameroon", 233 | "CL": "Chile", 234 | "CC": "Cocos Islands", 235 | "CA": "Canada", 236 | "CG": "Republic of the Congo", 237 | "CF": "Central African Republic", 238 | "CD": "Democratic Republic of the Congo", 239 | "CZ": "Czech Republic", 240 | "CY": "Cyprus", 241 | "CX": "Christmas Island", 242 | "CR": "Costa Rica", 243 | "CW": "Curacao", 244 | "CV": "Cape Verde", 245 | "CU": "Cuba", 246 | "SZ": "Swaziland", 247 | "SY": "Syria", 248 | "SX": "Sint Maarten", 249 | "KG": "Kyrgyzstan", 250 | "KE": "Kenya", 251 | "SS": "South Sudan", 252 | "SR": "Suriname", 253 | "KI": "Kiribati", 254 | "KH": "Cambodia", 255 | "KN": "Saint Kitts and Nevis", 256 | "KM": "Comoros", 257 | "ST": "Sao Tome and Principe", 258 | "SK": "Slovakia", 259 | "KR": "South Korea", 260 | "SI": "Slovenia", 261 | "KP": "North Korea", 262 | "KW": "Kuwait", 263 | "SN": "Senegal", 264 | "SM": "San Marino", 265 | "SL": "Sierra Leone", 266 | "SC": "Seychelles", 267 | "KZ": "Kazakhstan", 268 | "KY": "Cayman Islands", 269 | "SG": "Singapore", 270 | "SE": "Sweden", 271 | "SD": "Sudan", 272 | "DO": "Dominican Republic", 273 | "DM": "Dominica", 274 | "DJ": "Djibouti", 275 | "DK": "Denmark", 276 | "VG": "British Virgin Islands", 277 | "DE": "Germany", 278 | "YE": "Yemen", 279 | "DZ": "Algeria", 280 | "US": "United States", 281 | "UY": "Uruguay", 282 | "YT": "Mayotte", 283 | "UM": "United States Minor Outlying Islands", 284 | "LB": "Lebanon", 285 | "LC": "Saint Lucia", 286 | "LA": "Laos", 287 | "TV": "Tuvalu", 288 | "TW": "Taiwan", 289 | "TT": "Trinidad and Tobago", 290 | "TR": "Turkey", 291 | "LK": "Sri Lanka", 292 | "LI": "Liechtenstein", 293 | "LV": "Latvia", 294 | "TO": "Tonga", 295 | "LT": "Lithuania", 296 | "LU": "Luxembourg", 297 | "LR": "Liberia", 298 | "LS": "Lesotho", 299 | "TH": "Thailand", 300 | "TF": "French Southern Territories", 301 | "TG": "Togo", 302 | "TD": "Chad", 303 | "TC": "Turks and Caicos Islands", 304 | "LY": "Libya", 305 | "VA": "Vatican", 306 | "VC": "Saint Vincent and the Grenadines", 307 | "AE": "United Arab Emirates", 308 | "AD": "Andorra", 309 | "AG": "Antigua and Barbuda", 310 | "AF": "Afghanistan", 311 | "AI": "Anguilla", 312 | "VI": "U.S. Virgin Islands", 313 | "IS": "Iceland", 314 | "IR": "Iran", 315 | "AM": "Armenia", 316 | "AL": "Albania", 317 | "AO": "Angola", 318 | "AQ": "Antarctica", 319 | "AS": "American Samoa", 320 | "AR": "Argentina", 321 | "AU": "Australia", 322 | "AT": "Austria", 323 | "AW": "Aruba", 324 | "IN": "India", 325 | "AX": "Aland Islands", 326 | "AZ": "Azerbaijan", 327 | "IE": "Ireland", 328 | "ID": "Indonesia", 329 | "UA": "Ukraine", 330 | "QA": "Qatar", 331 | "MZ": "Mozambique", 332 | } 333 | 334 | var euCountries = []string{ 335 | "IE", "AT", "LT", "LU", "LV", "DE", "DK", "SE", "SI", "SK", "CZ", "CY", 336 | "NL", "FI", "FR", "MT", "ES", "IT", "EE", "PL", "PT", "HU", "HR", "GR", 337 | "RO", "BG", "BE", 338 | } 339 | 340 | var countriesFlags = map[string]CountryFlag{ 341 | "AD": {"🇦🇩", "U+1F1E6 U+1F1E9"}, 342 | "AE": {"🇦🇪", "U+1F1E6 U+1F1EA"}, 343 | "AF": {"🇦🇫", "U+1F1E6 U+1F1EB"}, 344 | "AG": {"🇦🇬", "U+1F1E6 U+1F1EC"}, 345 | "AI": {"🇦🇮", "U+1F1E6 U+1F1EE"}, 346 | "AL": {"🇦🇱", "U+1F1E6 U+1F1F1"}, 347 | "AM": {"🇦🇲", "U+1F1E6 U+1F1F2"}, 348 | "AO": {"🇦🇴", "U+1F1E6 U+1F1F4"}, 349 | "AQ": {"🇦🇶", "U+1F1E6 U+1F1F6"}, 350 | "AR": {"🇦🇷", "U+1F1E6 U+1F1F7"}, 351 | "AS": {"🇦🇸", "U+1F1E6 U+1F1F8"}, 352 | "AT": {"🇦🇹", "U+1F1E6 U+1F1F9"}, 353 | "AU": {"🇦🇺", "U+1F1E6 U+1F1FA"}, 354 | "AW": {"🇦🇼", "U+1F1E6 U+1F1FC"}, 355 | "AX": {"🇦🇽", "U+1F1E6 U+1F1FD"}, 356 | "AZ": {"🇦🇿", "U+1F1E6 U+1F1FF"}, 357 | "BA": {"🇧🇦", "U+1F1E7 U+1F1E6"}, 358 | "BB": {"🇧🇧", "U+1F1E7 U+1F1E7"}, 359 | "BD": {"🇧🇩", "U+1F1E7 U+1F1E9"}, 360 | "BE": {"🇧🇪", "U+1F1E7 U+1F1EA"}, 361 | "BF": {"🇧🇫", "U+1F1E7 U+1F1EB"}, 362 | "BG": {"🇧🇬", "U+1F1E7 U+1F1EC"}, 363 | "BH": {"🇧🇭", "U+1F1E7 U+1F1ED"}, 364 | "BI": {"🇧🇮", "U+1F1E7 U+1F1EE"}, 365 | "BJ": {"🇧🇯", "U+1F1E7 U+1F1EF"}, 366 | "BL": {"🇧🇱", "U+1F1E7 U+1F1F1"}, 367 | "BM": {"🇧🇲", "U+1F1E7 U+1F1F2"}, 368 | "BN": {"🇧🇳", "U+1F1E7 U+1F1F3"}, 369 | "BO": {"🇧🇴", "U+1F1E7 U+1F1F4"}, 370 | "BQ": {"🇧🇶", "U+1F1E7 U+1F1F6"}, 371 | "BR": {"🇧🇷", "U+1F1E7 U+1F1F7"}, 372 | "BS": {"🇧🇸", "U+1F1E7 U+1F1F8"}, 373 | "BT": {"🇧🇹", "U+1F1E7 U+1F1F9"}, 374 | "BV": {"🇧🇻", "U+1F1E7 U+1F1FB"}, 375 | "BW": {"🇧🇼", "U+1F1E7 U+1F1FC"}, 376 | "BY": {"🇧🇾", "U+1F1E7 U+1F1FE"}, 377 | "BZ": {"🇧🇿", "U+1F1E7 U+1F1FF"}, 378 | "CA": {"🇨🇦", "U+1F1E8 U+1F1E6"}, 379 | "CC": {"🇨🇨", "U+1F1E8 U+1F1E8"}, 380 | "CD": {"🇨🇩", "U+1F1E8 U+1F1E9"}, 381 | "CF": {"🇨🇫", "U+1F1E8 U+1F1EB"}, 382 | "CG": {"🇨🇬", "U+1F1E8 U+1F1EC"}, 383 | "CH": {"🇨🇭", "U+1F1E8 U+1F1ED"}, 384 | "CI": {"🇨🇮", "U+1F1E8 U+1F1EE"}, 385 | "CK": {"🇨🇰", "U+1F1E8 U+1F1F0"}, 386 | "CL": {"🇨🇱", "U+1F1E8 U+1F1F1"}, 387 | "CM": {"🇨🇲", "U+1F1E8 U+1F1F2"}, 388 | "CN": {"🇨🇳", "U+1F1E8 U+1F1F3"}, 389 | "CO": {"🇨🇴", "U+1F1E8 U+1F1F4"}, 390 | "CR": {"🇨🇷", "U+1F1E8 U+1F1F7"}, 391 | "CU": {"🇨🇺", "U+1F1E8 U+1F1FA"}, 392 | "CV": {"🇨🇻", "U+1F1E8 U+1F1FB"}, 393 | "CW": {"🇨🇼", "U+1F1E8 U+1F1FC"}, 394 | "CX": {"🇨🇽", "U+1F1E8 U+1F1FD"}, 395 | "CY": {"🇨🇾", "U+1F1E8 U+1F1FE"}, 396 | "CZ": {"🇨🇿", "U+1F1E8 U+1F1FF"}, 397 | "DE": {"🇩🇪", "U+1F1E9 U+1F1EA"}, 398 | "DJ": {"🇩🇯", "U+1F1E9 U+1F1EF"}, 399 | "DK": {"🇩🇰", "U+1F1E9 U+1F1F0"}, 400 | "DM": {"🇩🇲", "U+1F1E9 U+1F1F2"}, 401 | "DO": {"🇩🇴", "U+1F1E9 U+1F1F4"}, 402 | "DZ": {"🇩🇿", "U+1F1E9 U+1F1FF"}, 403 | "EC": {"🇪🇨", "U+1F1EA U+1F1E8"}, 404 | "EE": {"🇪🇪", "U+1F1EA U+1F1EA"}, 405 | "EG": {"🇪🇬", "U+1F1EA U+1F1EC"}, 406 | "EH": {"🇪🇭", "U+1F1EA U+1F1ED"}, 407 | "ER": {"🇪🇷", "U+1F1EA U+1F1F7"}, 408 | "ES": {"🇪🇸", "U+1F1EA U+1F1F8"}, 409 | "ET": {"🇪🇹", "U+1F1EA U+1F1F9"}, 410 | "FI": {"🇫🇮", "U+1F1EB U+1F1EE"}, 411 | "FJ": {"🇫🇯", "U+1F1EB U+1F1EF"}, 412 | "FK": {"🇫🇰", "U+1F1EB U+1F1F0"}, 413 | "FM": {"🇫🇲", "U+1F1EB U+1F1F2"}, 414 | "FO": {"🇫🇴", "U+1F1EB U+1F1F4"}, 415 | "FR": {"🇫🇷", "U+1F1EB U+1F1F7"}, 416 | "GA": {"🇬🇦", "U+1F1EC U+1F1E6"}, 417 | "GB": {"🇬🇧", "U+1F1EC U+1F1E7"}, 418 | "GD": {"🇬🇩", "U+1F1EC U+1F1E9"}, 419 | "GE": {"🇬🇪", "U+1F1EC U+1F1EA"}, 420 | "GF": {"🇬🇫", "U+1F1EC U+1F1EB"}, 421 | "GG": {"🇬🇬", "U+1F1EC U+1F1EC"}, 422 | "GH": {"🇬🇭", "U+1F1EC U+1F1ED"}, 423 | "GI": {"🇬🇮", "U+1F1EC U+1F1EE"}, 424 | "GL": {"🇬🇱", "U+1F1EC U+1F1F1"}, 425 | "GM": {"🇬🇲", "U+1F1EC U+1F1F2"}, 426 | "GN": {"🇬🇳", "U+1F1EC U+1F1F3"}, 427 | "GP": {"🇬🇵", "U+1F1EC U+1F1F5"}, 428 | "GQ": {"🇬🇶", "U+1F1EC U+1F1F6"}, 429 | "GR": {"🇬🇷", "U+1F1EC U+1F1F7"}, 430 | "GS": {"🇬🇸", "U+1F1EC U+1F1F8"}, 431 | "GT": {"🇬🇹", "U+1F1EC U+1F1F9"}, 432 | "GU": {"🇬🇺", "U+1F1EC U+1F1FA"}, 433 | "GW": {"🇬🇼", "U+1F1EC U+1F1FC"}, 434 | "GY": {"🇬🇾", "U+1F1EC U+1F1FE"}, 435 | "HK": {"🇭🇰", "U+1F1ED U+1F1F0"}, 436 | "HM": {"🇭🇲", "U+1F1ED U+1F1F2"}, 437 | "HN": {"🇭🇳", "U+1F1ED U+1F1F3"}, 438 | "HR": {"🇭🇷", "U+1F1ED U+1F1F7"}, 439 | "HT": {"🇭🇹", "U+1F1ED U+1F1F9"}, 440 | "HU": {"🇭🇺", "U+1F1ED U+1F1FA"}, 441 | "ID": {"🇮🇩", "U+1F1EE U+1F1E9"}, 442 | "IE": {"🇮🇪", "U+1F1EE U+1F1EA"}, 443 | "IL": {"🇮🇱", "U+1F1EE U+1F1F1"}, 444 | "IM": {"🇮🇲", "U+1F1EE U+1F1F2"}, 445 | "IN": {"🇮🇳", "U+1F1EE U+1F1F3"}, 446 | "IO": {"🇮🇴", "U+1F1EE U+1F1F4"}, 447 | "IQ": {"🇮🇶", "U+1F1EE U+1F1F6"}, 448 | "IR": {"🇮🇷", "U+1F1EE U+1F1F7"}, 449 | "IS": {"🇮🇸", "U+1F1EE U+1F1F8"}, 450 | "IT": {"🇮🇹", "U+1F1EE U+1F1F9"}, 451 | "JE": {"🇯🇪", "U+1F1EF U+1F1EA"}, 452 | "JM": {"🇯🇲", "U+1F1EF U+1F1F2"}, 453 | "JO": {"🇯🇴", "U+1F1EF U+1F1F4"}, 454 | "JP": {"🇯🇵", "U+1F1EF U+1F1F5"}, 455 | "KE": {"🇰🇪", "U+1F1F0 U+1F1EA"}, 456 | "KG": {"🇰🇬", "U+1F1F0 U+1F1EC"}, 457 | "KH": {"🇰🇭", "U+1F1F0 U+1F1ED"}, 458 | "KI": {"🇰🇮", "U+1F1F0 U+1F1EE"}, 459 | "KM": {"🇰🇲", "U+1F1F0 U+1F1F2"}, 460 | "KN": {"🇰🇳", "U+1F1F0 U+1F1F3"}, 461 | "KP": {"🇰🇵", "U+1F1F0 U+1F1F5"}, 462 | "KR": {"🇰🇷", "U+1F1F0 U+1F1F7"}, 463 | "KW": {"🇰🇼", "U+1F1F0 U+1F1FC"}, 464 | "KY": {"🇰🇾", "U+1F1F0 U+1F1FE"}, 465 | "KZ": {"🇰🇿", "U+1F1F0 U+1F1FF"}, 466 | "LA": {"🇱🇦", "U+1F1F1 U+1F1E6"}, 467 | "LB": {"🇱🇧", "U+1F1F1 U+1F1E7"}, 468 | "LC": {"🇱🇨", "U+1F1F1 U+1F1E8"}, 469 | "LI": {"🇱🇮", "U+1F1F1 U+1F1EE"}, 470 | "LK": {"🇱🇰", "U+1F1F1 U+1F1F0"}, 471 | "LR": {"🇱🇷", "U+1F1F1 U+1F1F7"}, 472 | "LS": {"🇱🇸", "U+1F1F1 U+1F1F8"}, 473 | "LT": {"🇱🇹", "U+1F1F1 U+1F1F9"}, 474 | "LU": {"🇱🇺", "U+1F1F1 U+1F1FA"}, 475 | "LV": {"🇱🇻", "U+1F1F1 U+1F1FB"}, 476 | "LY": {"🇱🇾", "U+1F1F1 U+1F1FE"}, 477 | "MA": {"🇲🇦", "U+1F1F2 U+1F1E6"}, 478 | "MC": {"🇲🇨", "U+1F1F2 U+1F1E8"}, 479 | "MD": {"🇲🇩", "U+1F1F2 U+1F1E9"}, 480 | "ME": {"🇲🇪", "U+1F1F2 U+1F1EA"}, 481 | "MF": {"🇲🇫", "U+1F1F2 U+1F1EB"}, 482 | "MG": {"🇲🇬", "U+1F1F2 U+1F1EC"}, 483 | "MH": {"🇲🇭", "U+1F1F2 U+1F1ED"}, 484 | "MK": {"🇲🇰", "U+1F1F2 U+1F1F0"}, 485 | "ML": {"🇲🇱", "U+1F1F2 U+1F1F1"}, 486 | "MM": {"🇲🇲", "U+1F1F2 U+1F1F2"}, 487 | "MN": {"🇲🇳", "U+1F1F2 U+1F1F3"}, 488 | "MO": {"🇲🇴", "U+1F1F2 U+1F1F4"}, 489 | "MP": {"🇲🇵", "U+1F1F2 U+1F1F5"}, 490 | "MQ": {"🇲🇶", "U+1F1F2 U+1F1F6"}, 491 | "MR": {"🇲🇷", "U+1F1F2 U+1F1F7"}, 492 | "MS": {"🇲🇸", "U+1F1F2 U+1F1F8"}, 493 | "MT": {"🇲🇹", "U+1F1F2 U+1F1F9"}, 494 | "MU": {"🇲🇺", "U+1F1F2 U+1F1FA"}, 495 | "MV": {"🇲🇻", "U+1F1F2 U+1F1FB"}, 496 | "MW": {"🇲🇼", "U+1F1F2 U+1F1FC"}, 497 | "MX": {"🇲🇽", "U+1F1F2 U+1F1FD"}, 498 | "MY": {"🇲🇾", "U+1F1F2 U+1F1FE"}, 499 | "MZ": {"🇲🇿", "U+1F1F2 U+1F1FF"}, 500 | "NA": {"🇳🇦", "U+1F1F3 U+1F1E6"}, 501 | "NC": {"🇳🇨", "U+1F1F3 U+1F1E8"}, 502 | "NE": {"🇳🇪", "U+1F1F3 U+1F1EA"}, 503 | "NF": {"🇳🇫", "U+1F1F3 U+1F1EB"}, 504 | "NG": {"🇳🇬", "U+1F1F3 U+1F1EC"}, 505 | "NI": {"🇳🇮", "U+1F1F3 U+1F1EE"}, 506 | "NL": {"🇳🇱", "U+1F1F3 U+1F1F1"}, 507 | "NO": {"🇳🇴", "U+1F1F3 U+1F1F4"}, 508 | "NP": {"🇳🇵", "U+1F1F3 U+1F1F5"}, 509 | "NR": {"🇳🇷", "U+1F1F3 U+1F1F7"}, 510 | "NU": {"🇳🇺", "U+1F1F3 U+1F1FA"}, 511 | "NZ": {"🇳🇿", "U+1F1F3 U+1F1FF"}, 512 | "OM": {"🇴🇲", "U+1F1F4 U+1F1F2"}, 513 | "PA": {"🇵🇦", "U+1F1F5 U+1F1E6"}, 514 | "PE": {"🇵🇪", "U+1F1F5 U+1F1EA"}, 515 | "PF": {"🇵🇫", "U+1F1F5 U+1F1EB"}, 516 | "PG": {"🇵🇬", "U+1F1F5 U+1F1EC"}, 517 | "PH": {"🇵🇭", "U+1F1F5 U+1F1ED"}, 518 | "PK": {"🇵🇰", "U+1F1F5 U+1F1F0"}, 519 | "PL": {"🇵🇱", "U+1F1F5 U+1F1F1"}, 520 | "PM": {"🇵🇲", "U+1F1F5 U+1F1F2"}, 521 | "PN": {"🇵🇳", "U+1F1F5 U+1F1F3"}, 522 | "PR": {"🇵🇷", "U+1F1F5 U+1F1F7"}, 523 | "PS": {"🇵🇸", "U+1F1F5 U+1F1F8"}, 524 | "PT": {"🇵🇹", "U+1F1F5 U+1F1F9"}, 525 | "PW": {"🇵🇼", "U+1F1F5 U+1F1FC"}, 526 | "PY": {"🇵🇾", "U+1F1F5 U+1F1FE"}, 527 | "QA": {"🇶🇦", "U+1F1F6 U+1F1E6"}, 528 | "RE": {"🇷🇪", "U+1F1F7 U+1F1EA"}, 529 | "RO": {"🇷🇴", "U+1F1F7 U+1F1F4"}, 530 | "RS": {"🇷🇸", "U+1F1F7 U+1F1F8"}, 531 | "RU": {"🇷🇺", "U+1F1F7 U+1F1FA"}, 532 | "RW": {"🇷🇼", "U+1F1F7 U+1F1FC"}, 533 | "SA": {"🇸🇦", "U+1F1F8 U+1F1E6"}, 534 | "SB": {"🇸🇧", "U+1F1F8 U+1F1E7"}, 535 | "SC": {"🇸🇨", "U+1F1F8 U+1F1E8"}, 536 | "SD": {"🇸🇩", "U+1F1F8 U+1F1E9"}, 537 | "SE": {"🇸🇪", "U+1F1F8 U+1F1EA"}, 538 | "SG": {"🇸🇬", "U+1F1F8 U+1F1EC"}, 539 | "SH": {"🇸🇭", "U+1F1F8 U+1F1ED"}, 540 | "SI": {"🇸🇮", "U+1F1F8 U+1F1EE"}, 541 | "SJ": {"🇸🇯", "U+1F1F8 U+1F1EF"}, 542 | "SK": {"🇸🇰", "U+1F1F8 U+1F1F0"}, 543 | "SL": {"🇸🇱", "U+1F1F8 U+1F1F1"}, 544 | "SM": {"🇸🇲", "U+1F1F8 U+1F1F2"}, 545 | "SN": {"🇸🇳", "U+1F1F8 U+1F1F3"}, 546 | "SO": {"🇸🇴", "U+1F1F8 U+1F1F4"}, 547 | "SR": {"🇸🇷", "U+1F1F8 U+1F1F7"}, 548 | "SS": {"🇸🇸", "U+1F1F8 U+1F1F8"}, 549 | "ST": {"🇸🇹", "U+1F1F8 U+1F1F9"}, 550 | "SV": {"🇸🇻", "U+1F1F8 U+1F1FB"}, 551 | "SX": {"🇸🇽", "U+1F1F8 U+1F1FD"}, 552 | "SY": {"🇸🇾", "U+1F1F8 U+1F1FE"}, 553 | "SZ": {"🇸🇿", "U+1F1F8 U+1F1FF"}, 554 | "TC": {"🇹🇨", "U+1F1F9 U+1F1E8"}, 555 | "TD": {"🇹🇩", "U+1F1F9 U+1F1E9"}, 556 | "TF": {"🇹🇫", "U+1F1F9 U+1F1EB"}, 557 | "TG": {"🇹🇬", "U+1F1F9 U+1F1EC"}, 558 | "TH": {"🇹🇭", "U+1F1F9 U+1F1ED"}, 559 | "TJ": {"🇹🇯", "U+1F1F9 U+1F1EF"}, 560 | "TK": {"🇹🇰", "U+1F1F9 U+1F1F0"}, 561 | "TL": {"🇹🇱", "U+1F1F9 U+1F1F1"}, 562 | "TM": {"🇹🇲", "U+1F1F9 U+1F1F2"}, 563 | "TN": {"🇹🇳", "U+1F1F9 U+1F1F3"}, 564 | "TO": {"🇹🇴", "U+1F1F9 U+1F1F4"}, 565 | "TR": {"🇹🇷", "U+1F1F9 U+1F1F7"}, 566 | "TT": {"🇹🇹", "U+1F1F9 U+1F1F9"}, 567 | "TV": {"🇹🇻", "U+1F1F9 U+1F1FB"}, 568 | "TW": {"🇹🇼", "U+1F1F9 U+1F1FC"}, 569 | "TZ": {"🇹🇿", "U+1F1F9 U+1F1FF"}, 570 | "UA": {"🇺🇦", "U+1F1FA U+1F1E6"}, 571 | "UG": {"🇺🇬", "U+1F1FA U+1F1EC"}, 572 | "UM": {"🇺🇲", "U+1F1FA U+1F1F2"}, 573 | "US": {"🇺🇸", "U+1F1FA U+1F1F8"}, 574 | "UY": {"🇺🇾", "U+1F1FA U+1F1FE"}, 575 | "UZ": {"🇺🇿", "U+1F1FA U+1F1FF"}, 576 | "VA": {"🇻🇦", "U+1F1FB U+1F1E6"}, 577 | "VC": {"🇻🇨", "U+1F1FB U+1F1E8"}, 578 | "VE": {"🇻🇪", "U+1F1FB U+1F1EA"}, 579 | "VG": {"🇻🇬", "U+1F1FB U+1F1EC"}, 580 | "VI": {"🇻🇮", "U+1F1FB U+1F1EE"}, 581 | "VN": {"🇻🇳", "U+1F1FB U+1F1F3"}, 582 | "VU": {"🇻🇺", "U+1F1FB U+1F1FA"}, 583 | "WF": {"🇼🇫", "U+1F1FC U+1F1EB"}, 584 | "WS": {"🇼🇸", "U+1F1FC U+1F1F8"}, 585 | "XK": {"🇽🇰", "U+1F1FD U+1F1F0"}, 586 | "YE": {"🇾🇪", "U+1F1FE U+1F1EA"}, 587 | "YT": {"🇾🇹", "U+1F1FE U+1F1F9"}, 588 | "ZA": {"🇿🇦", "U+1F1FF U+1F1E6"}, 589 | "ZM": {"🇿🇲", "U+1F1FF U+1F1F2"}, 590 | "ZW": {"🇿🇼", "U+1F1FF U+1F1FC"}, 591 | } 592 | 593 | var countriesCurrencies = map[string]CountryCurrency{ 594 | "AD": {"EUR", "€"}, 595 | "AE": {"AED", "د.إ"}, 596 | "AF": {"AFN", "؋"}, 597 | "AG": {"XCD", "$"}, 598 | "AI": {"XCD", "$"}, 599 | "AL": {"ALL", "L"}, 600 | "AM": {"AMD", "֏"}, 601 | "AO": {"AOA", "Kz"}, 602 | "AQ": {"", "$"}, 603 | "AR": {"ARS", "$"}, 604 | "AS": {"USD", "$"}, 605 | "AT": {"EUR", "€"}, 606 | "AU": {"AUD", "$"}, 607 | "AW": {"AWG", "ƒ"}, 608 | "AX": {"EUR", "€"}, 609 | "AZ": {"AZN", "₼"}, 610 | "BA": {"BAM", "KM"}, 611 | "BB": {"BBD", "$"}, 612 | "BD": {"BDT", "৳"}, 613 | "BE": {"EUR", "€"}, 614 | "BF": {"XOF", "CFA"}, 615 | "BG": {"BGN", "лв"}, 616 | "BH": {"BHD", ".د.ب"}, 617 | "BI": {"BIF", "FBu"}, 618 | "BJ": {"XOF", "CFA"}, 619 | "BL": {"EUR", "€"}, 620 | "BM": {"BMD", "$"}, 621 | "BN": {"BND", "$"}, 622 | "BO": {"BOB", "$b"}, 623 | "BQ": {"USD", "$"}, 624 | "BR": {"BRL", "R$"}, 625 | "BS": {"BSD", "$"}, 626 | "BT": {"BTN", "Nu."}, 627 | "BV": {"NOK", "kr"}, 628 | "BW": {"BWP", "P"}, 629 | "BY": {"BYR", "Br"}, 630 | "BZ": {"BZD", "BZ$"}, 631 | "CA": {"CAD", "$"}, 632 | "CC": {"AUD", "$"}, 633 | "CD": {"CDF", "FC"}, 634 | "CF": {"XAF", "FCFA"}, 635 | "CG": {"XAF", "FCFA"}, 636 | "CH": {"CHF", "CHF"}, 637 | "CI": {"XOF", "CFA"}, 638 | "CK": {"NZD", "$"}, 639 | "CL": {"CLP", "$"}, 640 | "CM": {"XAF", "FCFA"}, 641 | "CN": {"CNY", "¥"}, 642 | "CO": {"COP", "$"}, 643 | "CR": {"CRC", "₡"}, 644 | "CU": {"CUP", "₱"}, 645 | "CV": {"CVE", "$"}, 646 | "CW": {"ANG", "ƒ"}, 647 | "CX": {"AUD", "$"}, 648 | "CY": {"EUR", "€"}, 649 | "CZ": {"CZK", "Kč"}, 650 | "DE": {"EUR", "€"}, 651 | "DJ": {"DJF", "Fdj"}, 652 | "DK": {"DKK", "kr"}, 653 | "DM": {"XCD", "$"}, 654 | "DO": {"DOP", "RD$"}, 655 | "DZ": {"DZD", "دج"}, 656 | "EC": {"USD", "$"}, 657 | "EE": {"EUR", "€"}, 658 | "EG": {"EGP", "£"}, 659 | "EH": {"MAD", "MAD"}, 660 | "ER": {"ERN", "Nfk"}, 661 | "ES": {"EUR", "€"}, 662 | "ET": {"ETB", "Br"}, 663 | "FI": {"EUR", "€"}, 664 | "FJ": {"FJD", "$"}, 665 | "FK": {"FKP", "£"}, 666 | "FM": {"USD", "$"}, 667 | "FO": {"DKK", "kr"}, 668 | "FR": {"EUR", "€"}, 669 | "GA": {"XAF", "FCFA"}, 670 | "GB": {"GBP", "£"}, 671 | "GD": {"XCD", "$"}, 672 | "GE": {"GEL", "ლ"}, 673 | "GF": {"EUR", "€"}, 674 | "GG": {"GBP", "£"}, 675 | "GH": {"GHS", "GH₵"}, 676 | "GI": {"GIP", "£"}, 677 | "GL": {"DKK", "kr"}, 678 | "GM": {"GMD", "D"}, 679 | "GN": {"GNF", "FG"}, 680 | "GP": {"EUR", "€"}, 681 | "GQ": {"XAF", "FCFA"}, 682 | "GR": {"EUR", "€"}, 683 | "GS": {"GBP", "£"}, 684 | "GT": {"GTQ", "Q"}, 685 | "GU": {"USD", "$"}, 686 | "GW": {"XOF", "CFA"}, 687 | "GY": {"GYD", "$"}, 688 | "HK": {"HKD", "$"}, 689 | "HM": {"AUD", "$"}, 690 | "HN": {"HNL", "L"}, 691 | "HR": {"HRK", "kn"}, 692 | "HT": {"HTG", "G"}, 693 | "HU": {"HUF", "Ft"}, 694 | "ID": {"IDR", "Rp"}, 695 | "IE": {"EUR", "€"}, 696 | "IL": {"ILS", "₪"}, 697 | "IM": {"GBP", "£"}, 698 | "IN": {"INR", "₹"}, 699 | "IO": {"USD", "$"}, 700 | "IQ": {"IQD", "ع.د"}, 701 | "IR": {"IRR", "﷼"}, 702 | "IS": {"ISK", "kr"}, 703 | "IT": {"EUR", "€"}, 704 | "JE": {"GBP", "£"}, 705 | "JM": {"JMD", "J$"}, 706 | "JO": {"JOD", "JD"}, 707 | "JP": {"JPY", "¥"}, 708 | "KE": {"KES", "KSh"}, 709 | "KG": {"KGS", "лв"}, 710 | "KH": {"KHR", "៛"}, 711 | "KI": {"AUD", "$"}, 712 | "KM": {"KMF", "CF"}, 713 | "KN": {"XCD", "$"}, 714 | "KP": {"KPW", "₩"}, 715 | "KR": {"KRW", "₩"}, 716 | "KW": {"KWD", "KD"}, 717 | "KY": {"KYD", "$"}, 718 | "KZ": {"KZT", "₸"}, 719 | "LA": {"LAK", "₭"}, 720 | "LB": {"LBP", "£"}, 721 | "LC": {"XCD", "$"}, 722 | "LI": {"CHF", "CHF"}, 723 | "LK": {"LKR", "₨"}, 724 | "LR": {"LRD", "$"}, 725 | "LS": {"LSL", "M"}, 726 | "LT": {"LTL", "Lt"}, 727 | "LU": {"EUR", "€"}, 728 | "LV": {"EUR", "€"}, 729 | "LY": {"LYD", "LD"}, 730 | "MA": {"MAD", "MAD"}, 731 | "MC": {"EUR", "€"}, 732 | "MD": {"MDL", "lei"}, 733 | "ME": {"EUR", "€"}, 734 | "MF": {"EUR", "€"}, 735 | "MG": {"MGA", "Ar"}, 736 | "MH": {"USD", "$"}, 737 | "MK": {"MKD", "ден"}, 738 | "ML": {"XOF", "CFA"}, 739 | "MM": {"MMK", "K"}, 740 | "MN": {"MNT", "₮"}, 741 | "MO": {"MOP", "MOP$"}, 742 | "MP": {"USD", "$"}, 743 | "MQ": {"EUR", "€"}, 744 | "MR": {"MRO", "UM"}, 745 | "MS": {"XCD", "$"}, 746 | "MT": {"EUR", "€"}, 747 | "MU": {"MUR", "₨"}, 748 | "MV": {"MVR", "Rf"}, 749 | "MW": {"MWK", "MK"}, 750 | "MX": {"MXN", "$"}, 751 | "MY": {"MYR", "RM"}, 752 | "MZ": {"MZN", "MT"}, 753 | "NA": {"NAD", "$"}, 754 | "NC": {"XPF", "₣"}, 755 | "NE": {"XOF", "CFA"}, 756 | "NF": {"AUD", "$"}, 757 | "NG": {"NGN", "₦"}, 758 | "NI": {"NIO", "C$"}, 759 | "NL": {"EUR", "€"}, 760 | "NO": {"NOK", "kr"}, 761 | "NP": {"NPR", "₨"}, 762 | "NR": {"AUD", "$"}, 763 | "NU": {"NZD", "$"}, 764 | "NZ": {"NZD", "$"}, 765 | "OM": {"OMR", "﷼"}, 766 | "PA": {"PAB", "B/."}, 767 | "PE": {"PEN", "S/."}, 768 | "PF": {"XPF", "₣"}, 769 | "PG": {"PGK", "K"}, 770 | "PH": {"PHP", "₱"}, 771 | "PK": {"PKR", "₨"}, 772 | "PL": {"PLN", "zł"}, 773 | "PM": {"EUR", "€"}, 774 | "PN": {"NZD", "$"}, 775 | "PR": {"USD", "$"}, 776 | "PS": {"ILS", "₪"}, 777 | "PT": {"EUR", "€"}, 778 | "PW": {"USD", "$"}, 779 | "PY": {"PYG", "Gs"}, 780 | "QA": {"QAR", "﷼"}, 781 | "RE": {"EUR", "€"}, 782 | "RO": {"RON", "lei"}, 783 | "RS": {"RSD", "Дин."}, 784 | "RU": {"RUB", "₽"}, 785 | "RW": {"RWF", "R₣"}, 786 | "SA": {"SAR", "﷼"}, 787 | "SB": {"SBD", "$"}, 788 | "SC": {"SCR", "₨"}, 789 | "SD": {"SDG", "ج.س."}, 790 | "SE": {"SEK", "kr"}, 791 | "SG": {"SGD", "S$"}, 792 | "SH": {"SHP", "£"}, 793 | "SI": {"EUR", "€"}, 794 | "SJ": {"NOK", "kr"}, 795 | "SK": {"EUR", "€"}, 796 | "SL": {"SLL", "Le"}, 797 | "SM": {"EUR", "€"}, 798 | "SN": {"XOF", "CFA"}, 799 | "SO": {"SOS", "S"}, 800 | "SR": {"SRD", "$"}, 801 | "SS": {"SSP", "£"}, 802 | "ST": {"STD", "Db"}, 803 | "SV": {"USD", "$"}, 804 | "SX": {"ANG", "ƒ"}, 805 | "SY": {"SYP", "£"}, 806 | "SZ": {"SZL", "E"}, 807 | "TC": {"USD", "$"}, 808 | "TD": {"XAF", "FCFA"}, 809 | "TF": {"EUR", "€"}, 810 | "TG": {"XOF", "CFA"}, 811 | "TH": {"THB", "฿"}, 812 | "TJ": {"TJS", "SM"}, 813 | "TK": {"NZD", "$"}, 814 | "TL": {"USD", "$"}, 815 | "TM": {"TMT", "T"}, 816 | "TN": {"TND", "د.ت"}, 817 | "TO": {"TOP", "T$"}, 818 | "TR": {"TRY", "₺"}, 819 | "TT": {"TTD", "TT$"}, 820 | "TV": {"AUD", "$"}, 821 | "TW": {"TWD", "NT$"}, 822 | "TZ": {"TZS", "TSh"}, 823 | "UA": {"UAH", "₴"}, 824 | "UG": {"UGX", "USh"}, 825 | "UM": {"USD", "$"}, 826 | "US": {"USD", "$"}, 827 | "UY": {"UYU", "$U"}, 828 | "UZ": {"UZS", "лв"}, 829 | "VA": {"EUR", "€"}, 830 | "VC": {"XCD", "$"}, 831 | "VE": {"VEF", "Bs"}, 832 | "VG": {"USD", "$"}, 833 | "VI": {"USD", "$"}, 834 | "VN": {"VND", "₫"}, 835 | "VU": {"VUV", "VT"}, 836 | "WF": {"XPF", "₣"}, 837 | "WS": {"WST", "WS$"}, 838 | "XK": {"EUR", "€"}, 839 | "YE": {"YER", "﷼"}, 840 | "YT": {"EUR", "€"}, 841 | "ZA": {"ZAR", "R"}, 842 | "ZM": {"ZMK", "ZK"}, 843 | "ZW": {"ZWL", "$"}, 844 | } 845 | 846 | var continents = map[string]Continent{ 847 | "BD": {"AS", "Asia"}, 848 | "BE": {"EU", "Europe"}, 849 | "BF": {"AF", "Africa"}, 850 | "BG": {"EU", "Europe"}, 851 | "BA": {"EU", "Europe"}, 852 | "BB": {"NA", "North America"}, 853 | "WF": {"OC", "Oceania"}, 854 | "BL": {"NA", "North America"}, 855 | "BM": {"NA", "North America"}, 856 | "BN": {"AS", "Asia"}, 857 | "BO": {"SA", "South America"}, 858 | "BH": {"AS", "Asia"}, 859 | "BI": {"AF", "Africa"}, 860 | "BJ": {"AF", "Africa"}, 861 | "BT": {"AS", "Asia"}, 862 | "JM": {"NA", "North America"}, 863 | "BV": {"AN", "Antarctica"}, 864 | "BW": {"AF", "Africa"}, 865 | "WS": {"OC", "Oceania"}, 866 | "BQ": {"NA", "North America"}, 867 | "BR": {"SA", "South America"}, 868 | "BS": {"NA", "North America"}, 869 | "JE": {"EU", "Europe"}, 870 | "BY": {"EU", "Europe"}, 871 | "BZ": {"NA", "North America"}, 872 | "RU": {"EU", "Europe"}, 873 | "RW": {"AF", "Africa"}, 874 | "RS": {"EU", "Europe"}, 875 | "TL": {"OC", "Oceania"}, 876 | "RE": {"AF", "Africa"}, 877 | "TM": {"AS", "Asia"}, 878 | "TJ": {"AS", "Asia"}, 879 | "RO": {"EU", "Europe"}, 880 | "TK": {"OC", "Oceania"}, 881 | "GW": {"AF", "Africa"}, 882 | "GU": {"OC", "Oceania"}, 883 | "GT": {"NA", "North America"}, 884 | "GS": {"AN", "Antarctica"}, 885 | "GR": {"EU", "Europe"}, 886 | "GQ": {"AF", "Africa"}, 887 | "GP": {"NA", "North America"}, 888 | "JP": {"AS", "Asia"}, 889 | "GY": {"SA", "South America"}, 890 | "GG": {"EU", "Europe"}, 891 | "GF": {"SA", "South America"}, 892 | "GE": {"AS", "Asia"}, 893 | "GD": {"NA", "North America"}, 894 | "GB": {"EU", "Europe"}, 895 | "GA": {"AF", "Africa"}, 896 | "SV": {"NA", "North America"}, 897 | "GN": {"AF", "Africa"}, 898 | "GM": {"AF", "Africa"}, 899 | "GL": {"NA", "North America"}, 900 | "GI": {"EU", "Europe"}, 901 | "GH": {"AF", "Africa"}, 902 | "OM": {"AS", "Asia"}, 903 | "TN": {"AF", "Africa"}, 904 | "JO": {"AS", "Asia"}, 905 | "HR": {"EU", "Europe"}, 906 | "HT": {"NA", "North America"}, 907 | "HU": {"EU", "Europe"}, 908 | "HK": {"AS", "Asia"}, 909 | "HN": {"NA", "North America"}, 910 | "HM": {"AN", "Antarctica"}, 911 | "VE": {"SA", "South America"}, 912 | "PR": {"NA", "North America"}, 913 | "PS": {"AS", "Asia"}, 914 | "PW": {"OC", "Oceania"}, 915 | "PT": {"EU", "Europe"}, 916 | "SJ": {"EU", "Europe"}, 917 | "PY": {"SA", "South America"}, 918 | "IQ": {"AS", "Asia"}, 919 | "PA": {"NA", "North America"}, 920 | "PF": {"OC", "Oceania"}, 921 | "PG": {"OC", "Oceania"}, 922 | "PE": {"SA", "South America"}, 923 | "PK": {"AS", "Asia"}, 924 | "PH": {"AS", "Asia"}, 925 | "PN": {"OC", "Oceania"}, 926 | "PL": {"EU", "Europe"}, 927 | "PM": {"NA", "North America"}, 928 | "ZM": {"AF", "Africa"}, 929 | "EH": {"AF", "Africa"}, 930 | "EE": {"EU", "Europe"}, 931 | "EG": {"AF", "Africa"}, 932 | "ZA": {"AF", "Africa"}, 933 | "EC": {"SA", "South America"}, 934 | "IT": {"EU", "Europe"}, 935 | "VN": {"AS", "Asia"}, 936 | "SB": {"OC", "Oceania"}, 937 | "ET": {"AF", "Africa"}, 938 | "SO": {"AF", "Africa"}, 939 | "ZW": {"AF", "Africa"}, 940 | "SA": {"AS", "Asia"}, 941 | "ES": {"EU", "Europe"}, 942 | "ER": {"AF", "Africa"}, 943 | "ME": {"EU", "Europe"}, 944 | "MD": {"EU", "Europe"}, 945 | "MG": {"AF", "Africa"}, 946 | "MF": {"NA", "North America"}, 947 | "MA": {"AF", "Africa"}, 948 | "MC": {"EU", "Europe"}, 949 | "UZ": {"AS", "Asia"}, 950 | "MM": {"AS", "Asia"}, 951 | "ML": {"AF", "Africa"}, 952 | "MO": {"AS", "Asia"}, 953 | "MN": {"AS", "Asia"}, 954 | "MH": {"OC", "Oceania"}, 955 | "MK": {"EU", "Europe"}, 956 | "MU": {"AF", "Africa"}, 957 | "MT": {"EU", "Europe"}, 958 | "MW": {"AF", "Africa"}, 959 | "MV": {"AS", "Asia"}, 960 | "MQ": {"NA", "North America"}, 961 | "MP": {"OC", "Oceania"}, 962 | "MS": {"NA", "North America"}, 963 | "MR": {"AF", "Africa"}, 964 | "IM": {"EU", "Europe"}, 965 | "UG": {"AF", "Africa"}, 966 | "TZ": {"AF", "Africa"}, 967 | "MY": {"AS", "Asia"}, 968 | "MX": {"NA", "North America"}, 969 | "IL": {"AS", "Asia"}, 970 | "FR": {"EU", "Europe"}, 971 | "IO": {"AS", "Asia"}, 972 | "SH": {"AF", "Africa"}, 973 | "FI": {"EU", "Europe"}, 974 | "FJ": {"OC", "Oceania"}, 975 | "FK": {"SA", "South America"}, 976 | "FM": {"OC", "Oceania"}, 977 | "FO": {"EU", "Europe"}, 978 | "NI": {"NA", "North America"}, 979 | "NL": {"EU", "Europe"}, 980 | "NO": {"EU", "Europe"}, 981 | "NA": {"AF", "Africa"}, 982 | "VU": {"OC", "Oceania"}, 983 | "NC": {"OC", "Oceania"}, 984 | "NE": {"AF", "Africa"}, 985 | "NF": {"OC", "Oceania"}, 986 | "NG": {"AF", "Africa"}, 987 | "NZ": {"OC", "Oceania"}, 988 | "NP": {"AS", "Asia"}, 989 | "NR": {"OC", "Oceania"}, 990 | "NU": {"OC", "Oceania"}, 991 | "CK": {"OC", "Oceania"}, 992 | "XK": {"EU", "Europe"}, 993 | "CI": {"AF", "Africa"}, 994 | "CH": {"EU", "Europe"}, 995 | "CO": {"SA", "South America"}, 996 | "CN": {"AS", "Asia"}, 997 | "CM": {"AF", "Africa"}, 998 | "CL": {"SA", "South America"}, 999 | "CC": {"AS", "Asia"}, 1000 | "CA": {"NA", "North America"}, 1001 | "CG": {"AF", "Africa"}, 1002 | "CF": {"AF", "Africa"}, 1003 | "CD": {"AF", "Africa"}, 1004 | "CZ": {"EU", "Europe"}, 1005 | "CY": {"EU", "Europe"}, 1006 | "CX": {"AS", "Asia"}, 1007 | "CR": {"NA", "North America"}, 1008 | "CW": {"NA", "North America"}, 1009 | "CV": {"AF", "Africa"}, 1010 | "CU": {"NA", "North America"}, 1011 | "SZ": {"AF", "Africa"}, 1012 | "SY": {"AS", "Asia"}, 1013 | "SX": {"NA", "North America"}, 1014 | "KG": {"AS", "Asia"}, 1015 | "KE": {"AF", "Africa"}, 1016 | "SS": {"AF", "Africa"}, 1017 | "SR": {"SA", "South America"}, 1018 | "KI": {"OC", "Oceania"}, 1019 | "KH": {"AS", "Asia"}, 1020 | "KN": {"NA", "North America"}, 1021 | "KM": {"AF", "Africa"}, 1022 | "ST": {"AF", "Africa"}, 1023 | "SK": {"EU", "Europe"}, 1024 | "KR": {"AS", "Asia"}, 1025 | "SI": {"EU", "Europe"}, 1026 | "KP": {"AS", "Asia"}, 1027 | "KW": {"AS", "Asia"}, 1028 | "SN": {"AF", "Africa"}, 1029 | "SM": {"EU", "Europe"}, 1030 | "SL": {"AF", "Africa"}, 1031 | "SC": {"AF", "Africa"}, 1032 | "KZ": {"AS", "Asia"}, 1033 | "KY": {"NA", "North America"}, 1034 | "SG": {"AS", "Asia"}, 1035 | "SE": {"EU", "Europe"}, 1036 | "SD": {"AF", "Africa"}, 1037 | "DO": {"NA", "North America"}, 1038 | "DM": {"NA", "North America"}, 1039 | "DJ": {"AF", "Africa"}, 1040 | "DK": {"EU", "Europe"}, 1041 | "VG": {"NA", "North America"}, 1042 | "DE": {"EU", "Europe"}, 1043 | "YE": {"AS", "Asia"}, 1044 | "DZ": {"AF", "Africa"}, 1045 | "US": {"NA", "North America"}, 1046 | "UY": {"SA", "South America"}, 1047 | "YT": {"AF", "Africa"}, 1048 | "UM": {"OC", "Oceania"}, 1049 | "LB": {"AS", "Asia"}, 1050 | "LC": {"NA", "North America"}, 1051 | "LA": {"AS", "Asia"}, 1052 | "TV": {"OC", "Oceania"}, 1053 | "TW": {"AS", "Asia"}, 1054 | "TT": {"NA", "North America"}, 1055 | "TR": {"AS", "Asia"}, 1056 | "LK": {"AS", "Asia"}, 1057 | "LI": {"EU", "Europe"}, 1058 | "LV": {"EU", "Europe"}, 1059 | "TO": {"OC", "Oceania"}, 1060 | "LT": {"EU", "Europe"}, 1061 | "LU": {"EU", "Europe"}, 1062 | "LR": {"AF", "Africa"}, 1063 | "LS": {"AF", "Africa"}, 1064 | "TH": {"AS", "Asia"}, 1065 | "TF": {"AN", "Antarctica"}, 1066 | "TG": {"AF", "Africa"}, 1067 | "TD": {"AF", "Africa"}, 1068 | "TC": {"NA", "North America"}, 1069 | "LY": {"AF", "Africa"}, 1070 | "VA": {"EU", "Europe"}, 1071 | "VC": {"NA", "North America"}, 1072 | "AE": {"AS", "Asia"}, 1073 | "AD": {"EU", "Europe"}, 1074 | "AG": {"NA", "North America"}, 1075 | "AF": {"AS", "Asia"}, 1076 | "AI": {"NA", "North America"}, 1077 | "VI": {"NA", "North America"}, 1078 | "IS": {"EU", "Europe"}, 1079 | "IR": {"AS", "Asia"}, 1080 | "AM": {"AS", "Asia"}, 1081 | "AL": {"EU", "Europe"}, 1082 | "AO": {"AF", "Africa"}, 1083 | "AQ": {"AN", "Antarctica"}, 1084 | "AS": {"OC", "Oceania"}, 1085 | "AR": {"SA", "South America"}, 1086 | "AU": {"OC", "Oceania"}, 1087 | "AT": {"EU", "Europe"}, 1088 | "AW": {"NA", "North America"}, 1089 | "IN": {"AS", "Asia"}, 1090 | "AX": {"EU", "Europe"}, 1091 | "AZ": {"AS", "Asia"}, 1092 | "IE": {"EU", "Europe"}, 1093 | "ID": {"AS", "Asia"}, 1094 | "UA": {"EU", "Europe"}, 1095 | "QA": {"AS", "Asia"}, 1096 | "MZ": {"AF", "Africa"}, 1097 | } 1098 | --------------------------------------------------------------------------------