How can I use an API to detect if an IP address is a VPN in Go?

To detect if an IP address is a VPN using IP2Location.io in Go, you can use the IP2Location.io API to retrieve geolocation and related data.

  1. We'll assume that you have already installed Go and we won't cover that here. You will also need a paid subscription to the Security plan. Subscribe now!
  2. In the command line, run the below command inside an empty folder to create the project.
    Bash
    
    go mod init example
    			
  3. Save the below code into a file called example.go on your computer.
    Go
    
    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"strings"
    )
    
    type ResultObj struct {
    	Proxy struct {
    		IsVpn bool `json:"is_vpn"`
    	} `json:"proxy"`
    }
    
    type ErrorObj struct {
    	Error struct {
    		ErrorMessage string `json:"error_message"`
    	} `json:"error"`
    }
    
    func main() {
    	var res ResultObj
    	var ex ErrorObj
    	var key = "YOUR_API_KEY"
    	var ip = "8.8.8.8"
    
    	myUrl := "https://api.ip2location.io?format=json&ip=" + ip + "&key=" + key
    	resp, err := http.Get(myUrl)
    	if err != nil {
    		panic(err)
    	}
    	defer resp.Body.Close()
    
    	if resp.StatusCode == http.StatusOK {
    		bodyBytes, err := io.ReadAll(resp.Body)
    		if err != nil {
    			panic(err)
    		}
    		bodyStr := string(bodyBytes[:])
    		if strings.Contains(bodyStr, "is_vpn") {
    			err = json.Unmarshal(bodyBytes, &res)
    			if err != nil {
    				panic(err)
    			}
    			if res.Proxy.IsVpn {
    				fmt.Print("The IP " + ip + " is a VPN.")
    			} else {
    				fmt.Print("The IP " + ip + " is NOT a VPN.")
    			}
    		} else {
    			panic("ERROR: The is_vpn field requires a paid subscription to the Security plan.")
    		}
    	} else if resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusUnauthorized {
    		bodyBytes, err := io.ReadAll(resp.Body)
    		if err != nil {
    			panic(err)
    		}
    		bodyStr := string(bodyBytes[:])
    		if strings.Contains(bodyStr, "error_message") {
    			err = json.Unmarshal(bodyBytes, &ex)
    
    			if err != nil {
    				panic(err)
    			}
    			panic("ERROR: " + ex.Error.ErrorMessage)
    		}
    	} else {
    		panic("ERROR: Unable to call the API.")
    	}
    }
    			
  4. In the command line, run the below command.
    Bash
    
    go run example.go
    			

This script will check if the specified IP address is a VPN. Make sure to replace 8.8.8.8 with the IP address you want and replace YOUR_API_KEY to your own API key.

Other Languages

Unlock Location Insights For Free

Empower your applications with accurate IP geolocation information now.

Try It for Free