Skip to content

Integrations

Validate phone numbers and emails in Go

Check emails, phone numbers and IPs from Go with net/http only. Typed results, timeouts, retries on rate limits and a fail-open decision for signups.

Updated 2026-11-23

This recipe calls the API from Go with the standard library only. It gives you typed results for email, phone and IP checks, a deadline on every call and retries that respect the rate limit.

What you need

  • Go 1.21 or later.
  • A Qelka API key in the API_KEY environment variable. A sk_test_ key returns simulated results and never spends credits: see Test mode.
  • Server-side code only: see Authentication.

Steps

1. The client

go
package validate

import (
	"bytes"
	"context"
	"encoding/json"
	"math/rand"
	"net/http"
	"os"
	"strconv"
	"time"
)

const baseURL = "https://api.qelka.com/v1"

var httpClient = &http.Client{Timeout: 15 * time.Second}

type APIError struct {
	Status    int
	Type      string
	Message   string
	RequestID string
}

func (e *APIError) Error() string { return e.Type + ": " + e.Message }

type EmailResult struct {
	Status     string  `json:"status"`
	Reason     string  `json:"reason"`
	DidYouMean *string `json:"did_you_mean"`
}

type PhoneResult struct {
	Status string  `json:"status"`
	E164   *string `json:"e164"`
}

type IPResult struct {
	Flags struct {
		Tor bool `json:"tor"`
	} `json:"flags"`
	Risk struct {
		Level string `json:"level"`
	} `json:"risk"`
}

func call(ctx context.Context, path string, body any, out any) error {
	payload, err := json.Marshal(body)
	if err != nil {
		return err
	}
	for attempt := 1; ; attempt++ {
		request, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+path, bytes.NewReader(payload))
		if err != nil {
			return err
		}
		request.Header.Set("Authorization", "Bearer "+os.Getenv("API_KEY"))
		request.Header.Set("Content-Type", "application/json")
		response, err := httpClient.Do(request)
		if err != nil {
			return err
		}
		if response.StatusCode >= 200 && response.StatusCode < 300 {
			defer response.Body.Close()
			return json.NewDecoder(response.Body).Decode(out)
		}
		var failure struct {
			Error struct {
				Type    string `json:"type"`
				Message string `json:"message"`
			} `json:"error"`
		}
		_ = json.NewDecoder(response.Body).Decode(&failure)
		response.Body.Close()
		apiError := &APIError{response.StatusCode, failure.Error.Type, failure.Error.Message, response.Header.Get("X-Request-Id")}
		retryable := response.StatusCode == 429 || response.StatusCode == 500 || response.StatusCode == 502 || response.StatusCode == 503
		if !retryable || attempt == 4 {
			return apiError
		}
		wait := time.Duration(1<<(attempt-1))*time.Second + time.Duration(rand.Intn(250))*time.Millisecond
		if seconds, err := strconv.Atoi(response.Header.Get("Retry-After")); err == nil && seconds > 0 {
			wait = time.Duration(seconds) * time.Second
		}
		select {
		case <-time.After(wait):
		case <-ctx.Done():
			return ctx.Err()
		}
	}
}

func VerifyEmail(ctx context.Context, email string) (EmailResult, error) {
	var result EmailResult
	err := call(ctx, "/email", map[string]any{"email": email}, &result)
	return result, err
}

func ValidatePhone(ctx context.Context, phone, country string) (PhoneResult, error) {
	body := map[string]any{"phone": phone}
	if country != "" {
		body["country"] = country
	}
	var result PhoneResult
	err := call(ctx, "/phone", body, &result)
	return result, err
}

func LookupIP(ctx context.Context, ip string) (IPResult, error) {
	var result IPResult
	err := call(ctx, "/ip", map[string]any{"ip": ip}, &result)
	return result, err
}

The Retry-After header wins over the backoff on a 429. Every APIError carries the documented error type and the X-Request-Id. See Errors and Rate limits.

2. Decide on a signup

Put this in a second file of the same package.

go
package validate

import (
	"context"
	"errors"
	"fmt"
	"time"
)

type Verdict struct {
	Reject  bool
	Reasons []string
	Review  bool
	E164    string
}

func CheckSignup(ctx context.Context, email, phone, country, ip string) Verdict {
	ctx, cancel := context.WithTimeout(ctx, 12*time.Second)
	defer cancel()
	var verdict Verdict

	if result, err := VerifyEmail(ctx, email); err != nil {
		logFailure(err)
	} else if result.Status == "undeliverable" {
		verdict.Reject = true
		reason := "email cannot receive mail"
		if result.DidYouMean != nil {
			reason = "did you mean " + *result.DidYouMean + "?"
		}
		verdict.Reasons = append(verdict.Reasons, reason)
	} else if result.Status == "risky" && result.Reason == "disposable" {
		verdict.Review = true
	}

	if result, err := ValidatePhone(ctx, phone, country); err != nil {
		logFailure(err)
	} else if result.Status == "invalid" {
		verdict.Reject = true
		verdict.Reasons = append(verdict.Reasons, "phone number is not valid")
	} else if result.Status == "valid" && result.E164 != nil {
		verdict.E164 = *result.E164
	}

	if ip != "" {
		if result, err := LookupIP(ctx, ip); err != nil {
			var apiError *APIError
			if !(errors.As(err, &apiError) && apiError.Type == "unprocessable_input") {
				logFailure(err)
			}
		} else if result.Risk.Level == "high" || result.Flags.Tor {
			verdict.Review = true
		}
	}
	return verdict
}

func logFailure(err error) {
	var apiError *APIError
	if errors.As(err, &apiError) {
		fmt.Printf("validation skipped: %s status=%d request_id=%s\n", apiError.Type, apiError.Status, apiError.RequestID)
		return
	}
	fmt.Println("validation skipped:", err)
}

A failed call never sets Reject: the signup goes through and you re-check later. Only a clear negative answer blocks.

3. What the fields mean

Field Value Action
email.status undeliverable Reject, show did_you_mean
email.status risky Accept and flag, or reject disposables
email.status unknown Accept
phone.status valid Store e164
phone.status unknown Send country or ask for the + format
risk.level high Ask for extra verification

A 422 unprocessable_input on the IP is a private or loopback address, normal in local development, so it is ignored. For many values at once, POST /batch takes up to 100 items in one request: see the batch reference.

Frequently asked questions

Is there a Go client library?
There is no official Go package. The API is plain HTTPS and JSON, and the standard library covers it with net/http and encoding/json. The code below is a complete client of about eighty lines with typed results, a context timeout and a retry on rate limits. You can also generate a client from the public OpenAPI 3.1 document.
How do I set a timeout in Go?
Pass a context with a deadline to the request and set a Timeout on the http.Client. Email checks in full mode wait for a mail server, so give them around ten seconds. On a timeout, accept the signup and check again later instead of blocking the person.
Should I decode every field of the response?
Decode only the fields you act on. Go ignores unknown JSON fields by default, so adding fields to the API never breaks your code. The structs below keep the status, reason, did_you_mean, e164 and the IP risk level, which is what a signup decision needs.

Put this check in your product

Get an API key in under a minute. 100 free credits every month, no card required.

  • 100 free credits a month
  • No card
  • Test keys spend nothing
  • Cancel any time