# Email Validation API Code Samples in Go

URL: https://email-validation.org/docs/code-samples/go/
Updated: 2026-11-25

> Documentation index: https://email-validation.org/llms.txt

Copy-paste Go examples that validate one address, send the API key in the `Authorization` header, retry
`429` and `503` answers after `Retry-After` when the wait is at most 10 seconds (never `key_daily_cap`, which lasts
until the next UTC day), and report other errors with their code and request id. Each uses the free test address
`accepted@sandbox.email-validation.org`; replace it with a real address when you are ready. The same samples in other
languages: [all code samples](https://email-validation.org/docs/code-samples/).

Set your key first: `export EV_API_KEY="ev_live_…"`.

The samples call `https://api.email-validation.org`. For EU data residency, replace it with `https://api-eu.email-validation.org`, or pass the SDK's EU base URL constant;
there `/v1/validate` takes `POST` only ([EU data residency](https://email-validation.org/docs/eu-data-residency/)).

## With the official SDK

The [official Go SDK](https://email-validation.org/docs/sdks/go/) does the retries, timeouts and error mapping
for you: one call validates an address and every failure arrives as a typed error. There are official SDKs for JavaScript/TypeScript, Python, Go, PHP, Ruby, C#, Rust and Swift; those for Java, Kotlin, Dart, Elixir, C and Perl are built and tested and coming soon to their package registries. The plain
HTTP samples further down call the API directly.

**Go**

```go
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	"email-validation.org/go/emailvalidation"
)

func main() {
	client, err := emailvalidation.New(os.Getenv("EV_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}
	result, err := client.Validate(context.Background(), "accepted@sandbox.email-validation.org", nil)
	var apiErr *emailvalidation.Error
	switch {
	case err == nil:
		fmt.Println(result.Status, result.Reason, result.Action) // valid accepted send
	case errors.Is(err, emailvalidation.ErrInsufficientCredits):
		fmt.Println("buy credits; nothing was charged")
	case errors.As(err, &apiErr):
		fmt.Println(apiErr.Code, apiErr.RequestID)
	default:
		log.Fatal(err)
	}
}
```

## Validate an address

**Go**

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"strconv"
	"time"
)

type Result struct {
	Email       string `json:"email"`
	Status      string `json:"status"`
	Reason      string `json:"reason"`
	Action      string `json:"action"`
	CreditsUsed int    `json:"credits_used"`
	RequestID   string `json:"request_id"`
}

type apiError struct {
	Error struct {
		Code      string `json:"code"`
		Message   string `json:"message"`
		RequestID string `json:"request_id"`
	} `json:"error"`
}

var client = &http.Client{Timeout: 20 * time.Second}

// maxWait: never wait out a long Retry-After (key_daily_cap lasts until the next UTC day).
const maxWait = 10

func validate(email string, attempts int) (*Result, error) {
	payload, err := json.Marshal(map[string]string{"email": email})
	if err != nil {
		return nil, err
	}
	for attempt := 1; ; attempt++ {
		req, err := http.NewRequest(http.MethodPost, "https://api.email-validation.org/v1/validate", bytes.NewReader(payload))
		if err != nil {
			return nil, err
		}
		req.Header.Set("Authorization", "Bearer "+os.Getenv("EV_API_KEY"))
		req.Header.Set("Content-Type", "application/json")
		res, err := client.Do(req)
		if err != nil {
			return nil, err
		}
		if res.StatusCode == http.StatusOK {
			defer res.Body.Close()
			var result Result
			if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
				return nil, err
			}
			return &result, nil
		}
		var e apiError
		_ = json.NewDecoder(res.Body).Decode(&e)
		res.Body.Close()
		wait, err := strconv.Atoi(res.Header.Get("Retry-After"))
		if err != nil || wait < 1 {
			wait = 1
		}
		retryable := (res.StatusCode == http.StatusTooManyRequests || res.StatusCode == http.StatusServiceUnavailable) &&
			e.Error.Code != "key_daily_cap" && wait <= maxWait
		if retryable && attempt < attempts {
			time.Sleep(time.Duration(wait) * time.Second)
			continue
		}
		return nil, fmt.Errorf("%s: %s (%s)", e.Error.Code, e.Error.Message, e.Error.RequestID)
	}
}

func main() {
	result, err := validate("accepted@sandbox.email-validation.org", 3)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(result.Status, result.Reason, result.Action, result.CreditsUsed)
}
```

## Verify a webhook

**Go**

```go
package webhooks

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"math"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// Verify checks a delivery. Read the body with io.ReadAll(r.Body) before calling it.
func Verify(body []byte, h http.Header, secret string, tolerance time.Duration) error {
	id, ts, sigs := h.Get("webhook-id"), h.Get("webhook-timestamp"), h.Get("webhook-signature")
	if id == "" || ts == "" || sigs == "" {
		return errors.New("missing webhook headers")
	}
	sec, err := strconv.ParseInt(ts, 10, 64)
	if err != nil || math.Abs(float64(time.Now().Unix()-sec)) > tolerance.Seconds() {
		return errors.New("timestamp outside tolerance")
	}
	key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
	if err != nil {
		return err
	}
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(id + "." + ts + "."))
	mac.Write(body)
	expected := mac.Sum(nil)
	for _, entry := range strings.Split(sigs, " ") {
		version, sig, ok := strings.Cut(entry, ",")
		if !ok || version != "v1" {
			continue
		}
		given, err := base64.StdEncoding.DecodeString(sig)
		if err == nil && hmac.Equal(given, expected) {
			return nil
		}
	}
	return errors.New("no valid signature")
}
```

## Other calls

- Read the credit balance: samples in curl, JavaScript and Python ([all code samples](https://email-validation.org/docs/code-samples/#credits)).
- Create a bulk job: samples in curl, JavaScript and Python ([all code samples](https://email-validation.org/docs/code-samples/#bulk)).

## Notes

- Use `POST` with a JSON body; it keeps addresses out of URLs and logs.
- Set the HTTP timeout to about 20 seconds: a check may take up to 15 seconds (10 by default).
- A `200` answer with the status `unknown` is a normal, free result, not an error.
- Every endpoint, field and error: the [API reference](https://email-validation.org/docs/api-reference/).
