Coder Social home page Coder Social logo

ipinfo / go Goto Github PK

View Code? Open in Web Editor NEW
115.0 16.0 22.0 173 KB

Go library for IPinfo API (IP geolocation and other types of IP data)

Home Page: https://pkg.go.dev/github.com/ipinfo/go/v2

License: Apache License 2.0

Go 99.42% Shell 0.58%
go ipinfo ip-geolocation ip-address ip-data

go's Introduction

IPinfo IPinfo Go Client Library

License Go Reference

This is the official Go client library for the 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:

  • IP to Geolocation (city, region, country, postal code, latitude, and longitude)
  • IP to ASN (ISP or network operator, associated domain name, and type, such as business, hosting, or company)
  • IP to Company (the name and domain of the business that uses the IP address)
  • IP to Carrier (the name of the mobile carrier and MNC and MCC for that carrier if the IP is used exclusively for mobile traffic)

Check all the data we have for your IP address here.

Getting Started

You'll need an IPinfo API access token, which you can get by signing up for a free account at https://ipinfo.io/signup.

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

You can find the full package-level documentation here: https://pkg.go.dev/github.com/ipinfo/go/v2/ipinfo

Installation

go get github.com/ipinfo/go/v2/ipinfo

Quickstart

Basic usage of the package.

package main

import (
	"fmt"
	"log"
	"net"
	"github.com/ipinfo/go/v2/ipinfo"
)

func main() {
	const token = "YOUR_TOKEN"
	
	// params: httpClient, cache, token. `http.DefaultClient` and no cache will be used in case of `nil`.
	client := ipinfo.NewClient(nil, nil, token)

	const ip_address = "8.8.8.8"
	info, err := client.GetIPInfo(net.ParseIP(ip_address))

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(info)
	// Output: {8.8.8.8 dns.google false true Mountain View California US United States...
}

This data is available even on our free tier which includes up to 50,000 IP geolocation requests per month.

Authentication

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

const token = "YOUR_TOKEN"
// params: httpClient, cache, token. `http.DefaultClient` and no cache will be used in case of `nil`.
client := ipinfo.NewClient(nil, nil, token)

Internationalization

Country Name

info.Country returns the ISO 3166 country code and info.CountryName returns the entire conuntry name:

fmt.Println(info.Country)
// Output: US
fmt.Println(info.CountryName)
// Output: United States

European Union (EU) Country

info.IsEU returns a boolean response to see if a country is a European Union country or not.

fmt.Println(info.IsEU)
// Output: false

Country Flag

Get country flag as an emoji and its Unicode value with info.CountryFlag.Emoji and info.CountryFlag.Unicode respectively.

fmt.Println(info.CountryFlag.Emoji)
// Output: ๐Ÿ‡ณ๐Ÿ‡ฟ 
fmt.Println(info.CountryFlag.Unicode)
// Output: "U+1F1F3 U+1F1FF"

Country Flag URL

Get the link of a country's flag image.

fmt.Println(info.CountryFlagURL)
// Output: https://cdn.ipinfo.io/static/images/countries-flags/US.svg"

Country Currency

Get country's currency code and its symbol with info.CountryCurrency.Code and info.CountryCurrency.Symbol respectively.

fmt.Println(info.CountryCurrency.Code)
// Output: USD 
fmt.Println(info.CountryCurrency.Symbol)
// Output: $

Continent

Get the IP's continent code and its name with info.Continent.Code and info.Continent.Name respectively.

fmt.Println(info.Continent.Code)
// Output: NA 
fmt.Println(info.Continent.Name)
// Output: North America

Map IP Address

You can map up to 500,000 IP addresses all at once using the GetIPMap command. You can input:

  • IP addresses (IPV4 and IPV6 both)
  • IP Ranges or Netblock
  • ASN

After the operation, you will be presented with a URL to a map generated on the IPinfo website.

IP Map Code:

package main

import (
	"fmt"
	"log"
	"net"

	"github.com/ipinfo/go/v2/ipinfo"
)

func main() {
	client := ipinfo.NewClient(nil, nil, "YOUR_TOKEN")
	result, err := client.GetIPMap(
		[]net.IP{
			net.ParseIP("136.111.157.61"),
			net.ParseIP("231.163.78.134"),
			// ...
			net.ParseIP("228.128.213.179"),
			net.ParseIP("103.172.175.76"),
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result)
}

Result:

See the output example map: https://ipinfo.io/tools/map/f27c7d40-3ff0-4ac2-878f-8d953dbcd3c8

Summarize IP Address

Summarize IP addresses with GetIPSummary and output a report.

package main

import (
	"fmt"
	"log"
	"net"

	"github.com/ipinfo/go/v2/ipinfo"
)

func main() {
	client := ipinfo.NewClient(nil, nil, "YOUR_TOKEN")
	result, err := client.GetIPSummary(
		[]net.IP{
			net.ParseIP("171.164.236.38"),
			net.ParseIP("206.132.224.214"),
			// ....
			net.ParseIP("208.191.89.104"),
			net.ParseIP("81.216.14.76"),
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result)
	// Ouptut: {100 100 map[CN:7 DE:4 JP:12 MX:3 US:32] map[Columbus, ...

}

Batch Operations / Bulk Lookup

You can do batch lookups or bulk lookups quite easily as well. The inputs supported:

  • IP addresses. IPV4 and IPV6 both
  • ASN
  • Specific field endpoint of an IP address e.g. 8.8.8.8/country
package main

import (
	"fmt"
	"log"
	"time"
	"github.com/ipinfo/go/v2/ipinfo"
	"github.com/ipinfo/go/v2/ipinfo/cache"
)

func main() {
	client := ipinfo.NewClient(
		nil,
		ipinfo.NewCache(cache.NewInMemory().WithExpiration(5*time.Minute)),
		"YOUR_TOKEN",
	)

	// batchResult will contain all the batch lookup data
	batchResult, err := client.GetBatch(
		[]string{
			"104.193.114.182",                    // you can pass IPV4 address
			"8.8.8.8/country",                    // you can get specific information
			"AS36811",                            // you can lookup ASN details
			"2a03:2880:f10a:83:face:b00c:0:25de", // IPV6 address
		},
		ipinfo.BatchReqOpts{
			BatchSize:       2,
			TimeoutPerBatch: 0,
			TimeoutTotal:    5,
		},
	)
	if err != nil {
		log.Fatal(err)
	}
	for k, v := range batchResult {
		fmt.Printf("k=%v v=%v\n", k, v)
	}
}

Examples of Batch / Bulk Lookup:

The loop declaration in the batch lookup showcases the "caching" capability of the IPinfo package.

Other Libraries

There are official IPinfo client 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.

About IPinfo

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.

image

go's People

Contributors

abdullahdevrel avatar abu-usama avatar ahmadmujahid2k avatar awaismslm avatar deltwalrus avatar harisabdullah avatar rm-umar avatar sobanmahmood avatar st-polina avatar umanshahzad avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go's Issues

Fix go mod path

Fix go mod path so it has a /v2 at the end so that new module tooling works properly.

GetIpInfoBatch: panic: interface conversion: interface {} is *interface {}, not *ipinfo.Core

The GetIPInfoBatch method does not work, it always creates this error interface conversion: interface {} is *interface {}, not *ipinfo.Core

Example code:

        client := ipinfo.NewClient(nil, nil, "<TOKEN>")

	batchResult, err := client.GetIPInfoBatch(
		[]net.IP{
				net.ParseIP("1.1.1.1"),
				net.ParseIP("8.8.8.8"),
		},
		ipinfo.BatchReqOpts{
			BatchSize:       10,
			TimeoutPerBatch: 0,
			TimeoutTotal:    5,
		},
	)

	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(batchResult)

Expected output: IP Info for the batch

Actual output:

panic: interface conversion: interface {} is *interface {}, not *ipinfo.Core

goroutine 1 [running]:
github.com/ipinfo/go/v2/ipinfo.(*Client).GetIPStrInfoBatch(0x140000b6490?, {0x140000cc1c0?, 0x0?, 0x10?}, {0x0, 0x0, 0x5, 0x0, 0x0})
        /Users/jc/.gvm/pkgsets/go1.18.1/global/pkg/mod/github.com/ipinfo/go/[email protected]/ipinfo/batch.go:310 +0x17c
github.com/ipinfo/go/v2/ipinfo.(*Client).GetIPInfoBatch(0x100394ccc?, {0x140000c5e48, 0x2, 0x11?}, {0x0, 0x0, 0x5, 0x0, 0x0})
        /Users/jc/.gvm/pkgsets/go1.18.1/global/pkg/mod/github.com/ipinfo/go/[email protected]/ipinfo/batch.go:282 +0x8c
main.GenerateIpinfoMap({0x10046b5a0?, 0x140000c5f50?, 0x140000c5f28?})
        /Users/jc/Dev/ipinfo_api.go:22 +0x250
main.main()
        /Users/jc/Dev/main.go:55 +0xd4
exit status 2

Create IsEU function on Core object

We added a package-level isEU function, but that isn't what we really want. We want isEU to be a function on the Core object so that users can run that on their core objects to get the result.

Map integration

Create a simple function that accepts an IP list (max 500k) and returns the JSON response from https://ipinfo.io/maps.

Add optional IP selection handler

Add an optional IP selection handler to the SDK client initialization step which accepts the request context and expects returning an IP.

Add a default handler for this which looks at the X-Forwarded-For header and falls back to the source IP.

The resulting IP is the IP for which details are fetched.

panics and errors when running `batch-*` examples

$ go run batch-asn/main.go 
doing lookup #0
panic: interface conversion: interface {} is *interface {}, not *ipinfo.ASNDetails

goroutine 1 [running]:
github.com/ipinfo/go/v2/ipinfo.(*Client).GetASNDetailsBatch(0x6efba0, {0xc0000621e0, 0x696c48, 0x11}, {0x127ed0, 0x1, 0x1, 0x70})
        /home/petr/go/pkg/mod/github.com/ipinfo/go/[email protected]/ipinfo/batch.go:325 +0x170
main.main()
        /home/petr/go/pkg/mod/github.com/ipinfo/go/[email protected]/example/batch-asn/main.go:21 +0x1e5
exit status 2

$ go run batch-core-netip/main.go 
doing lookup #0
panic: interface conversion: interface {} is *interface {}, not *ipinfo.Core

goroutine 1 [running]:
github.com/ipinfo/go/v2/ipinfo.(*Client).GetIPStrInfoBatch(0xc0000b2470, {0xc0000d41c0, 0x0, 0x4b1500}, {0x10, 0xc, 0x1, 0x70})
        /home/petr/go/pkg/mod/github.com/ipinfo/go/[email protected]/ipinfo/batch.go:294 +0x170
github.com/ipinfo/go/v2/ipinfo.(*Client).GetIPInfoBatch(0x69476b, {0xc0000d1ee0, 0x2, 0x11}, {0xd1ea0, 0x1, 0x1, 0xa0})
        /home/petr/go/pkg/mod/github.com/ipinfo/go/[email protected]/ipinfo/batch.go:266 +0xa5
main.main()
        /home/petr/go/pkg/mod/github.com/ipinfo/go/[email protected]/example/batch-core-netip/main.go:22 +0x257
exit status 2

$ go run batch-core-str/main.go 
doing lookup #0
panic: interface conversion: interface {} is *interface {}, not *ipinfo.Core

goroutine 1 [running]:
github.com/ipinfo/go/v2/ipinfo.(*Client).GetIPStrInfoBatch(0x6efb80, {0xc0000621e0, 0x696c2c, 0x11}, {0x127ed0, 0x1, 0x1, 0x70})
        /home/petr/go/pkg/mod/github.com/ipinfo/go/[email protected]/ipinfo/batch.go:294 +0x170
main.main()
        /home/petr/go/pkg/mod/github.com/ipinfo/go/[email protected]/example/batch-core-str/main.go:21 +0x1e5
exit status 2

$ go run batch-generic/main.go 
doing lookup #0
k=error v=0xc0004ce060

doing lookup #1
k=error v=0xc0004ce1a0

doing lookup #2
k=error v=0xc000091700

Too many arguments in call to ipinfo.NewClient

I am using the standard example code as stated in ipinfo/go.
But I get the following errors:

I am using:
Go Version: go 1.19
Router: Gin (https://github.com/gin-gonic/gin)

Code:
client := ipinfo.NewClient(nil, nil, token)

Error:

too many arguments in call to ipinfo.NewClient
	have (nil, nil, string)
	want (*http.Client)

And

Code:
info, err := client.GetIPInfo(net.ParseIP(ip_address))

Error:
client.GetIPInfo undefined (type *ipinfo.Client has no field or method GetIPInfo)

The function ipinfo.NewClient takes 1 argument instead of 3.
Is the documentation/readme outdated?

Change User-Agent string

According to the guidelines:

The wrapper should send all requests with the following user agent format:

IPinfoClient/Language/Version

For example:

IPinfoClient/Go/1.0

Limit the number of simultaneous batch chunk reqs

When we send a batch request for X amount of IPs, and X > 1000, we start chunking X into groups of 1000, and make requests for each group separately to the IPinfo batch endpoint, because the endpoint does not accept a size greater than 1000.

However, we do this all at once for all chunks: if there were 500k IPs as input, 500 simultaneous, parallel requests would be made. The issue with this is we may exceed the file descriptor limit of the user; we had this issue with e.g. the CLI.

Implement an upper-limit on the number of simultaneous, parallel requests being made.

IPv6 error

package main

import (
	"fmt"
	"log"
	"net"

	"github.com/ipinfoio/go-ipinfo/ipinfo"
)

func main() {
	_, err := ipinfo.GetInfo(net.ParseIP("2a03:2880:f10a:83:face:b00c:0:25de"))
	if err != nil {
		log.Fatal(err)
	}
}
$ go run main.go
2017/10/31 14:16:12 parse 2a03:2880:f10a:83:face:b00c:0:25de: first path segment in URL cannot contain colon
exit status 1

go get install method is deprecated

$ go get github.com/ipinfo/go/v2/ipinfo
go: go.mod file not found in current directory or any parent directory.
        'go get' is no longer supported outside a module.
        To build and install a command, use 'go install' with a version,
        like 'go install example.com/cmd@latest'
        For more information, see https://golang.org/doc/go-get-install-deprecation
        or run 'go help get' or 'go help install'.

Move to "go" repo

Should be ipinfo/go in github, to match our other repos, which are just named after the language

Use versioned cache key

Make sure the cache key contains a number to indicate the version of the cached data. Data changes that change what's expected in cached data require a version change.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.