Skip to content
iplogs.comSign up
Guide · Last updated 2026-11-19

VPN, proxy, and Tor detection in Go

A complete Go client for the IPLogs API, written against the standard library alone. We type the verdict, call the API with net/http under context.WithTimeout, add a per-IP cache and a middleware, batch-score through /v1/bulk-check, and test it all against an httptest.Server. The API takes no key, so there is no SDK to pull in.

By Mehmood Ali ·

How do you add VPN detection to a Go service?

Use only the standard library. Declare a Verdict type with the four values clean, suspicious, vpn_likely and vpn_detected, plus a CheckResponse struct, so a changed response shape fails loudly instead of producing silent zero values. Call POST https://iplogs.com/v1/check with net/http and a request context carrying a 10-second timeout, which is slightly longer than the API's roughly 8-second probing ceiling so slow addresses still get a full verdict. The API is free and needs no key or SDK. Read the client IP from X-Forwarded-For, X-Real-IP or CF-Connecting-IP only when the connection comes from your own proxy. Wrap the call in HTTP middleware that stores the verdict in the request context and fails open on errors. Cache verdicts per IP for five minutes with sync.Map, or Redis across several instances. For offline scoring, POST up to 100 addresses to /v1/bulk-check. Test everything against an httptest.Server that returns canned JSON.

Type the verdict

package iplogs

type Verdict string

const (
    VerdictClean       Verdict = "clean"
    VerdictSuspicious  Verdict = "suspicious"
    VerdictVPNLikely   Verdict = "vpn_likely"
    VerdictVPNDetected Verdict = "vpn_detected"
)

type IPInfo struct {
    IP                 string   `json:"ip"`
    ASN                string   `json:"asn,omitempty"`
    Org                string   `json:"org,omitempty"`
    Country            string   `json:"country,omitempty"`
    CountryCode        string   `json:"country_code,omitempty"`
    IsVPN              bool     `json:"is_vpn,omitempty"`
    VPNProvider        string   `json:"vpn_provider,omitempty"`
    VPNProviderSources []string `json:"vpn_provider_sources,omitempty"`
}

type Signal struct {
    Type    string  `json:"type"`
    Weight  float64 `json:"weight"`
    Matched bool    `json:"matched"`
    Detail  string  `json:"detail"`
}

type CheckResponse struct {
    Verdict    Verdict  `json:"verdict"`
    Score      float64  `json:"score"`
    IsVPN      bool     `json:"is_vpn"`
    Confidence float64  `json:"confidence"`
    Signals    []Signal `json:"signals"`
    IPInfo     IPInfo   `json:"ip_info"`
    RequestID  string   `json:"request_id"`
}

Quick start

package iplogs

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

type Client struct {
    BaseURL    string
    HTTPClient *http.Client
}

func New() *Client {
    return &Client{
        BaseURL: "https://iplogs.com",
        // No client-wide Timeout: it would also cut off the 95s bulk call.
        // Each method sets its own deadline on the context instead.
        HTTPClient: &http.Client{},
    }
}

func (c *Client) Check(ctx context.Context, ip string) (*CheckResponse, error) {
    body, _ := json.Marshal(map[string]string{"ip": ip})
    // The API stops probing at ~8s; 10s leaves room for the network.
    ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
    defer cancel()

    req, err := http.NewRequestWithContext(ctx, http.MethodPost,
        c.BaseURL+"/v1/check", bytes.NewReader(body))
    if err != nil {
        return nil, err
    }
    req.Header.Set("Content-Type", "application/json")

    resp, err := c.HTTPClient.Do(req)
    if err != nil {
        return nil, fmt.Errorf("iplogs: %w", err)
    }
    defer resp.Body.Close()
    if resp.StatusCode >= 400 {
        return nil, fmt.Errorf("iplogs: HTTP %d", resp.StatusCode)
    }
    var out CheckResponse
    if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
        return nil, fmt.Errorf("iplogs decode: %w", err)
    }
    return &out, nil
}

Create one *http.Client per process and reuse it. Pass a context.Context on every call so the request is cancelled if the caller goes away. The 10-second deadline is deliberately above the API's ~8-second probing ceiling: a new IP usually answers in about 2 seconds, but the slowest datacenter IPs take 5–7, and a shorter timeout would drop exactly those.

Read the visitor IP from a trusted proxy

package iplogs

import (
    "net"
    "net/http"
    "strings"
)

// trustedProxies are the immediate-peer addresses whose proxy headers
// we trust. Caddy and Nginx running on the same host are 127.0.0.1 or ::1.
var trustedProxies = map[string]struct{}{
    "127.0.0.1": {},
    "::1":       {},
}

func ClientIP(r *http.Request) string {
    peer, _, err := net.SplitHostPort(r.RemoteAddr)
    if err != nil {
        peer = r.RemoteAddr
    }
    if _, ok := trustedProxies[peer]; !ok {
        return peer // direct request: ignore any proxy headers
    }
    if cf := r.Header.Get("CF-Connecting-IP"); cf != "" {
        return strings.TrimSpace(cf)
    }
    // Caddy / Nginx append the real peer at the end. Read the LAST entry.
    if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
        parts := strings.Split(xff, ",")
        return strings.TrimSpace(parts[len(parts)-1])
    }
    if xri := r.Header.Get("X-Real-IP"); xri != "" {
        return strings.TrimSpace(xri)
    }
    return peer
}

HTTP middleware

package iplogs

import (
    "context"
    "net/http"
)

type ctxKey struct{}

// Middleware attaches the IPLogs verdict to the request context. Per-handler
// code reads it with iplogs.From(ctx) and decides policy.
func (c *Client) Middleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ip := ClientIP(r)
        if ip != "" {
            if v, err := c.Check(r.Context(), ip); err == nil {
                r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, v))
            }
            // Fail open: missing verdict means per-handler default policy.
        }
        next.ServeHTTP(w, r)
    })
}

func From(ctx context.Context) *CheckResponse {
    v, _ := ctx.Value(ctxKey{}).(*CheckResponse)
    return v
}

Per-IP cache

package iplogs

import (
    "context"
    "sync"
    "time"
)

type cachedVerdict struct {
    resp *CheckResponse
    at   time.Time
}

type CachedClient struct {
    *Client
    cache sync.Map // ip -> cachedVerdict
    ttl   time.Duration
}

// NewCached starts an eviction goroutine that runs until ctx is cancelled.
func NewCached(ctx context.Context, c *Client, ttl time.Duration) *CachedClient {
    cc := &CachedClient{Client: c, ttl: ttl}
    go cc.evict(ctx)
    return cc
}

func (c *CachedClient) Check(ctx context.Context, ip string) (*CheckResponse, error) {
    if v, ok := c.cache.Load(ip); ok {
        cv := v.(cachedVerdict)
        if time.Since(cv.at) < c.ttl {
            return cv.resp, nil
        }
    }
    resp, err := c.Client.Check(ctx, ip)
    if err != nil {
        return nil, err
    }
    c.cache.Store(ip, cachedVerdict{resp: resp, at: time.Now()})
    return resp, nil
}

// evict drops expired entries once per TTL so the map can't grow forever.
func (c *CachedClient) evict(ctx context.Context) {
    t := time.NewTicker(c.ttl)
    defer t.Stop()
    for {
        select {
        case <-ctx.Done():
            return
        case <-t.C:
            c.cache.Range(func(k, v any) bool {
                if time.Since(v.(cachedVerdict).at) >= c.ttl {
                    // Only delete if no fresher verdict was stored meanwhile.
                    c.cache.CompareAndDelete(k, v)
                }
                return true
            })
        }
    }
}

Five minutes is a sensible TTL. On a fleet, replace sync.Map with a Redis client and SET key value EX 300 so every worker shares one cache. In a single process, sync.Map is already safe for concurrent use, so no extra mutex is needed, and the eviction goroutine keeps the map down to the IPs seen in the last one or two TTLs.

Batch scoring with /v1/bulk-check

type BulkRow struct {
    IP          string  `json:"ip"`
    Verdict     Verdict `json:"verdict,omitempty"`
    Score       float64 `json:"score"`
    IsVPN       bool    `json:"is_vpn"`
    VPNProvider string  `json:"vpn_provider,omitempty"`
    CountryCode string  `json:"country_code,omitempty"`
    ASN         string  `json:"asn,omitempty"`
    Org         string  `json:"org,omitempty"`
    Error       string  `json:"error,omitempty"`
}

type bulkResp struct {
    Total      int       `json:"total"`
    DurationMs int64     `json:"duration_ms"`
    Results    []BulkRow `json:"results"`
}

func (c *Client) BulkCheck(ctx context.Context, ips []string) ([]BulkRow, error) {
    body, _ := json.Marshal(map[string][]string{"ips": ips})
    ctx, cancel := context.WithTimeout(ctx, 95*time.Second)
    defer cancel()

    req, _ := http.NewRequestWithContext(ctx, http.MethodPost,
        c.BaseURL+"/v1/bulk-check", bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    resp, err := c.HTTPClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    var out bulkResp
    if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
        return nil, err
    }
    return out.Results, nil
}

/v1/bulk-check takes up to 100 IPs per request, so split longer lists into chunks and loop over them. Each row is kept deliberately small, which brings a 100-IP batch to ~10 KB instead of ~30 KB.

Testing without hitting the network

package iplogs

import (
    "context"
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestCheckClean(t *testing.T) {
    srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte(`{"verdict":"clean","score":0,"is_vpn":false,
            "confidence":0.15,"signals":[],"ip_info":{"ip":"1.1.1.1"},
            "request_id":"req_test"}`))
    }))
    defer srv.Close()

    c := &Client{BaseURL: srv.URL, HTTPClient: srv.Client()}
    out, err := c.Check(context.Background(), "1.1.1.1")
    if err != nil { t.Fatal(err) }
    if out.Verdict != VerdictClean {
        t.Errorf("got %q, want clean", out.Verdict)
    }
}

FAQ

Do I need an SDK or library to call IPLogs from Go?

No. net/http, encoding/json and context from the standard library cover it in around 30 lines. A dependency for one POST to one URL isn't worth it, and staying on the stdlib keeps the code small and easy to audit.

Should I share an http.Client across requests?

Yes. Reuse one http.Client (or fasthttp client) for the whole process. A new client per request leaks connections and defeats connection pooling. If you expect bursts, give it a Transport with sensible MaxIdleConns and IdleConnTimeout values.

How should I cache verdicts in Go?

For a single binary, a sync.Map plus a goroutine that evicts expired entries is enough. With several instances, use Redis with EX 300, keyed by the IP string. A verdict is a small JSON object, so the memory it takes is trivial next to the round trip it saves.

Where should the verdict call sit in a Go HTTP server?

In a middleware. It runs the check, puts the verdict in the request context, and leaves each handler to apply its own policy. chi.Router and a plain http.Handler are wrapped the same way, with a middleware that decorates the request and passes it on to the next handler.

How do I test the integration without hitting the network?

Start an httptest.Server that returns canned JSON and point the client at it through a configurable base URL. The verdict shape is stable: Verdict (clean / suspicious / vpn_likely / vpn_detected), Score (0–1), IsVPN, IPInfo, Signals[]. Assert on the URL, method and body the client sends.

The full schema is in the API docs. If part of your stack is in another language, the Python guide and Node.js guide cover the same integration, and the accuracy benchmark has the published false-positive rate.