# Go SDK

Source: https://docs.rocketverifier.com/sdks/go

> Run go get github.com/rocketverifier/sdk-go, create a client with rocketverifier.New(apiKey) and call rv.Verify(ctx, email, nil). The module uses only the standard library, takes a context on every call, retries safely with a stable Idempotency-Key and returns typed errors you match with errors.Is.

`github.com/rocketverifier/sdk-go` is the official Go client for the RocketVerifier API. It covers real-time verification, bulk jobs from a list or a file, progress and downloads, webhooks, monitors, credits and RocketVerifier Connect OAuth, with no dependencies outside the standard library.

## Install the SDK

Add the module to your project. The package name is `rocketverifier`.

Terminal:

```bash
go get github.com/rocketverifier/sdk-go
```

Go:

```go
import rocketverifier "github.com/rocketverifier/sdk-go"
```

## Create a client

`rocketverifier.New(apiKey, opts...)` returns a `*Client` that is safe for concurrent use. Read the key from `ROCKETVERIFIER_API_KEY` so it never lands in source control.

Go:

```go
rv, err := rocketverifier.New(
	os.Getenv("ROCKETVERIFIER_API_KEY"),
	rocketverifier.WithTimeout(15*time.Second),
	rocketverifier.WithMaxRetries(5),
)
if err != nil {
	log.Fatal(err)
}
```

`New` returns an error when the key is empty. Live keys start with `rv_live_`; sandbox keys start with `rv_test_` and accept only [sandbox addresses](https://docs.rocketverifier.com/sandbox). See [authentication](https://docs.rocketverifier.com/authentication).

| Option | Default | What it does |
| --- | --- | --- |
| `WithBaseURL(url)` | `https://api.rocketverifier.com` | API base URL. |
| `WithTimeout(d)` | `30 * time.Second` | Timeout per attempt. Each retry gets the full timeout again. |
| `WithMaxRetries(n)` | `3` | Retries on 429, timeouts and network errors. `0` turns retries off. |
| `WithHTTPClient(hc)` | `&http.Client{}` | Your own `*http.Client`, for proxies or tracing. |
| `WithHeader(key, value)` | none | Extra header on every request, applied last. |
| `WithRefreshToken(token)` | none | OAuth refresh token for automatic refresh. |
| `WithOAuth(o)` | none | The `*OAuth` helper used for automatic refresh. |
| `WithTokenRefreshHandler(fn)` | none | Called with the new `*TokenSet` after a refresh. Persist it here. |

## Verify an email

`rv.Verify(ctx, email, opts)` checks one address with [`POST /v1/verify`](https://docs.rocketverifier.com/api/verify) and returns a `*VerificationResult`. Branch on `Status` and read `SubStatus` for the reason.

Go:

```go
ctx := context.Background()
result, err := rv.Verify(ctx, "deliverable@sandbox.rocketverifier.com", nil)
if err != nil {
	log.Fatal(err)
}

switch result.Status {
case rocketverifier.StatusDeliverable:
	// send
case rocketverifier.StatusRisky:
	fmt.Println("review:", result.SubStatus)
case rocketverifier.StatusUndeliverable:
	if result.DidYouMean != nil {
		fmt.Println("did you mean", *result.DidYouMean)
	}
case rocketverifier.StatusUnknown:
	// free: check again later
}
```

`VerifyOptions` has `IdempotencyKey` (a random key is used when empty) and `Timeout`, the server side verification timeout in seconds. The SDK accepts 5 to 60 and grows the HTTP timeout to cover it. Input without an `@` returns a validation error before any request is sent. The [reading results guide](https://docs.rocketverifier.com/results) explains every status and `sub_status`.

### Result fields

| Field | Type | API field |
| --- | --- | --- |
| `Email`, `Status`, `Reason` | `string` | `email`, `status`, `reason` |
| `SubStatus` | `string` | `sub_status`, `"none"` when not specific |
| `Score` | `float64` | `score`, 0 to 100 |
| `CatchAllVerdict` | `*string` | `catch_all_verdict` |
| `DidYouMean` | `*string` | `did_you_mean` |
| `VerifiedAt` | `*string` | `verified_at` |
| `Provider` | `*string` | `provider` |
| `Domain` | `DomainInfo` | `Name`, `AcceptAll *bool`, `Disposable bool`, `Free bool`, `AcceptAllConfidence`, `AcceptAllVerdict` |
| `Account` | `*AccountInfo` | `Role bool`, `Disabled *bool`, `FullMailbox *bool` |
| `DNS` | `*DNSInfo` | `Type`, `Record` |
| `AuthenticationScore` | `*float64` | `authentication_score` |
| `DeliverabilityTier` | `*string` | `deliverability_tier` |
| `Toxic`, `Abuse` | `*string` | `"yes"`, `"no"` or `"unknown"` |
| `SpamTrap` | `bool` | `spam_trap` |
| `Activity`, `Evidence` | `map[string]any` | `activity`, `evidence` |
| `Raw` | `json.RawMessage` | The full response body |

`IsDeliverable()`, `IsUndeliverable()`, `IsRisky()` and `IsUnknown()` test the status. The `"yes"`, `"no"` and `"unknown"` flags become Go booleans: plain `bool` fields are `true` only for `"yes"`, and `*bool` fields are `nil` when the server reports `"unknown"`. Read any other field from `Raw`.

## Verify a list in bulk

`rv.Batch` runs bulk jobs of up to 100,000 unique addresses. The [batch API reference](https://docs.rocketverifier.com/api/batch) covers the endpoints.

Go:

```go
job, err := rv.Batch.Create(ctx, &rocketverifier.BatchCreateParams{
	Name:   "October signups",
	Emails: []string{"deliverable@sandbox.rocketverifier.com", "undeliverable@sandbox.rocketverifier.com"},
})
if err != nil {
	log.Fatal(err)
}

done, err := rv.Batch.Wait(ctx, job.JobID, &rocketverifier.WaitOptions{
	PollInterval: 3 * time.Second,
	OnProgress: func(j *rocketverifier.BatchJob) {
		fmt.Printf("%d/%d\n", j.ProcessedEmails, j.TotalEmails)
	},
})
```

- **Create:** `Batch.Create(ctx, *BatchCreateParams{Emails, Name, IdempotencyKey})` returns `JobID`, `TotalEmails`, `EstimatedTimeSeconds`, `CreditsToUse` and `CreditsRemaining`. The limit applies to unique addresses.
- **Wait:** `Batch.Wait(ctx, jobID, *WaitOptions)` polls every `PollInterval` (5 seconds) until the job is completed, failed or cancelled, or reaches `awaiting_confirmation`. Past `Timeout` (5 minutes) it returns an error with `Kind == KindTimeout`, and it stops early when `ctx` is done.
- **Get:** `Batch.Get(ctx, jobID)` returns a `*BatchJob` with counts, `ProgressPercent` and timestamps. `IsFinished()` and `IsAwaitingConfirmation()` test the status.
- **Progress:** `Batch.Progress(ctx, jobID)` returns a `*JobProgress` with `Total`, `Processed`, `Remaining`, `Percent`, `Counts`, `CountsByStatus`, `RatePerMinute` and `ETASeconds`.
- **List:** `Batch.List(ctx, *ListOptions{Page, Limit, Status})` returns a `*JobsPage`. `Limit` defaults to 20, up to 100.
- **Cancel:** `Batch.Delete(ctx, jobID)` or `Batch.Cancel(ctx, jobID)` returns `RefundedCredits` for unprocessed addresses.

### Read results

`Batch.Results` returns one page, `Batch.Iterate` walks every row and `Batch.AllResults` returns them all in one slice.

Go:

```go
it := rv.Batch.Iterate(ctx, jobID, &rocketverifier.ResultsOptions{Classification: "valid"})
for it.Next() {
	r := it.Result()
	fmt.Println(r.Email, r.SubStatus)
}
if err := it.Err(); err != nil {
	log.Fatal(err)
}
```

`ResultsOptions` has `Page`, `Limit` (100 for `Results`, 1000 for `Iterate` and `AllResults`, up to 1000) and `Classification`. Each `JobResult` has `Email`, `Classification`, `IsValid`, `IsDisposable`, `IsCatchAll`, `IsRoleBased`, `ConfidenceScore`, `SubStatus` and `VerifiedAt`.

### Download results

Three methods download the full results of a completed job. `DownloadOptions` has `Format`, `Filter` (`deliverable`, `undeliverable`, `risky`, `unknown` or `send_safe`) and `IncludeOriginal`.

Go:

```go
csv, err := rv.Batch.Download(ctx, jobID, nil)                                  // raw CSV bytes
rows, err := rv.Batch.DownloadRows(ctx, jobID, &rocketverifier.DownloadOptions{Filter: "send_safe"})
data, err := rv.Batch.DownloadJSON(ctx, jobID, nil)                             // JobID, Results
```

`DownloadRows` parses the CSV with `ParseDownloadCSV`: boolean columns become `bool` and score columns become numbers.

## Upload a file

`Batch.Upload(ctx, *UploadParams)` creates a job from a CSV, TSV, TXT or XLSX file of up to 50 MB, or from a public HTTPS URL. Set exactly one of `File`, `FilePath` or `SourceURL`. See [bulk upload](https://docs.rocketverifier.com/api/bulk-upload).

Go:

```go
up, err := rv.Batch.Upload(ctx, &rocketverifier.UploadParams{
	FilePath:    "contacts.csv",
	EmailColumn: "Work Email",
	Preview:     true,
})
if err != nil {
	log.Fatal(err)
}

preview, err := rv.Batch.Preview(ctx, up.JobID, false)
for err == nil && preview.Pending {
	time.Sleep(2 * time.Second)
	preview, err = rv.Batch.Preview(ctx, up.JobID, false)
}
fmt.Println(preview.Preview["estimated_bounce_rate"])

confirmed, err := rv.Batch.Confirm(ctx, up.JobID, "")
```

- `UploadParams` also takes `File` (an `io.Reader`) with `Filename`, `Name`, `ColumnMapping`, `CallbackURL`, `ContentType` and `IdempotencyKey`. `EmailColumn` is a header name or a 0-based index.
- `BatchUploadResult` has `JobID`, `Status`, `Preview`, `StatusURL`, `ProgressURL` and `CallbackSecret`, which is set once when you pass `CallbackURL`.
- `Batch.Preview(ctx, jobID, refresh)` returns the free list health estimate as a map, with `Pending` set while it is computing.
- `Batch.Confirm(ctx, jobID, idempotencyKey)` charges and starts the job. A job is never charged twice, so it is safe to retry.

## Check a domain, credits and account

Go:

```go
info, err := rv.Domain.Check(ctx, "northwind.io") // Domain, MXRecords, Provider, Disposable, HasValidMX
credits, err := rv.Credits(ctx)                   // Credits, UsedToday, UsedThisMonth
me, err := rv.Me(ctx)                             // Email, AccountType, Organization, Credits, AuthType, Scopes, App
```

`Me` calls [`GET /v1/me`](https://docs.rocketverifier.com/api/account). `me.IsOAuth()` is true for OAuth tokens.

## Manage monitors

`rv.Monitors` schedules list health re-verification and SPF, DKIM and DMARC checks. See the [monitors API](https://docs.rocketverifier.com/api/monitors).

Go:

```go
m, err := rv.Monitors.Create(ctx, &rocketverifier.MonitorCreateParams{
	Name:   "Brand domain",
	Type:   rocketverifier.MonitorTypeDomainAuth,
	Domain: "northwind.io",
})
```

| Method | What it does |
| --- | --- |
| `Create(ctx, *MonitorCreateParams)` | `Frequency` defaults to `weekly`, `AlertThreshold` to 5. `domain_auth` needs `Domain`; `list_health` needs `Emails`. |
| `List(ctx)`, `Get(ctx, id)` | Return `Monitor` values. |
| `Update(ctx, id, *MonitorUpdateParams)` | Pointer fields left `nil` are unchanged. |
| `Delete(ctx, id)` | Removes the monitor. |
| `Runs(ctx, id, *PageOptions)` | A `*MonitorRunsPage`, most recent first. |
| `RunNow(ctx, id, idempotencyKey)` | Runs it immediately. `list_health` runs cost 1 credit per address. |

## Manage webhook endpoints

`rv.Webhooks` registers HTTPS endpoints for events such as `job.completed`. It needs the `webhooks:manage` scope. See the [webhooks API](https://docs.rocketverifier.com/api/webhooks).

Go:

```go
hook, err := rv.Webhooks.Create(ctx, &rocketverifier.WebhookCreateParams{
	URL:    "https://northwind.io/hooks/rocketverifier",
	Events: []string{rocketverifier.EventJobCompleted, rocketverifier.EventJobFailed},
})
// Store hook.Secret now: it is shown only once.
```

The service also has `ListEvents`, `List`, `Get`, `Update` (with `*WebhookUpdateParams`), `Delete`, `Test`, `Logs` (with `*WebhookLogsOptions{Page, Limit, Status}`) and `RotateSecret`. Event names are exported as `EventJobCompleted`, `EventJobFailed`, `EventCreditsLow`, `EventCreditsDepleted`, `EventEmailVerified` and `EventMonitorAlert`.

## Verify webhook signatures

`ConstructEvent` checks the `X-RocketVerifier-Signature` header and the timestamp, then returns the event. Pass the raw body exactly as received.

Go:

```go
http.HandleFunc("/hooks/rocketverifier", func(w http.ResponseWriter, r *http.Request) {
	body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	header := strings.Join(r.Header.Values(rocketverifier.SignatureHeader), ",")

	event, err := rocketverifier.ConstructEvent(body, header, os.Getenv("ROCKETVERIFIER_WEBHOOK_SECRET"))
	if err != nil {
		http.Error(w, "invalid signature", http.StatusBadRequest)
		return
	}
	if event.Event == rocketverifier.EventJobCompleted {
		var data struct {
			JobID string `json:"job_id"`
		}
		_ = event.DecodeData(&data)
		log.Printf("job %s finished", data.JobID)
	}
	w.WriteHeader(http.StatusOK)
})
```

- `VerifySignature(rawBody, header, secret, opts...)` returns `nil` or a `*WebhookSignatureError` whose `Reason` is `missing_secret`, `missing_header`, `malformed_header`, `timestamp_out_of_tolerance` or `signature_mismatch`. `ConstructEvent` adds `invalid_json`.
- `WithTolerance(d)` changes the 300 second window; `WithNow(t)` fixes the clock in tests.
- `GenerateSignatureHeader(rawBody, secret, timestamp)` builds a valid header for testing your endpoint.

## Act for a user with OAuth

`NewOAuth` runs the RocketVerifier Connect authorization code flow with PKCE; `NewWithAccessToken` calls the API for the connected user. The [OAuth guide](https://docs.rocketverifier.com/oauth) covers app registration.

Go:

```go
oauth, err := rocketverifier.NewOAuth(rocketverifier.OAuthConfig{
	ClientID:     os.Getenv("RV_CLIENT_ID"),
	ClientSecret: os.Getenv("RV_CLIENT_SECRET"),
	RedirectURI:  "https://northwind.io/rocketverifier/callback",
})

auth, err := oauth.AuthorizeURL(rocketverifier.AuthorizeParams{Scopes: []string{"verify:bulk", "account:read"}})
// store auth.State and auth.CodeVerifier, redirect to auth.URL

tokens, err := oauth.ExchangeCode(ctx, code, auth.CodeVerifier, "")

userRV, err := rocketverifier.NewWithAccessToken(tokens.AccessToken,
	rocketverifier.WithRefreshToken(tokens.RefreshToken),
	rocketverifier.WithOAuth(oauth),
	rocketverifier.WithTokenRefreshHandler(func(ctx context.Context, t *rocketverifier.TokenSet) error {
		return saveTokens(ctx, userID, t)
	}),
)
```

- `OAuthConfig` also takes `Issuer` (default `https://app.rocketverifier.com`), `TokenEndpointAuthMethod` (default `client_secret_basic`), `HTTPClient` and `Timeout`. Leave `ClientSecret` empty for public clients.
- `OAuth` has `AuthorizeURL`, `ExchangeCode`, `Refresh`, `Revoke` and `Introspect`. `TokenSet` holds `AccessToken`, `RefreshToken`, `TokenType`, `ExpiresIn`, `ExpiresAt` (`time.Time`) and `Scopes`.
- On a 401 `invalid_token` the client refreshes once, retries and calls your handler. Without refresh configured, it returns an error matching `ErrInvalidToken`. A rejected refresh token returns an `*OAuthError` with `ErrorCode == "invalid_grant"`.
- `rv.SetTokens(accessToken, refreshToken)` swaps in tokens refreshed elsewhere.

## Handle errors

Every API failure is a `*rocketverifier.Error` with `Kind`, `Code`, `StatusCode`, `Message`, `Details`, `RetryAfter` and `Err`. Match it with `errors.Is` and the sentinel errors.

| Sentinel | `Kind` | Returned when |
| --- | --- | --- |
| `ErrAuthentication` | `KindAuthentication` | 401. Also matches invalid token errors. |
| `ErrInvalidToken` | `KindInvalidToken` | 401 `invalid_token` for an OAuth token that cannot be refreshed. |
| `ErrInsufficientCredits` | `KindInsufficientCredits` | 402, or code `insufficient_credits` (including the 403 at zero balance). |
| `ErrRateLimited` | `KindRateLimit` | 429 after all retries. `RetryAfter` holds the seconds. |
| `ErrValidation` | `KindValidation` | 400 or 422, or input rejected before sending. |
| `ErrPermissionDenied` | `KindPermissionDenied` | 403, such as a missing scope. |
| `ErrNotFound` | `KindNotFound` | 404. |
| `ErrTimeout` | `KindTimeout` | The request or `Batch.Wait` timed out. `StatusCode` is 408. |
| `ErrNetwork` | `KindNetwork` | The connection failed. `StatusCode` is 0. |

Go:

```go
_, err := rv.Verify(ctx, "maya@northwind.io", nil)
var apiErr *rocketverifier.Error
switch {
case errors.Is(err, rocketverifier.ErrInsufficientCredits):
	// top up
case errors.As(err, &apiErr) && apiErr.Kind == rocketverifier.KindRateLimit:
	time.Sleep(time.Duration(apiErr.RetryAfter) * time.Second)
case err != nil:
	log.Fatal(err)
}
```

The [errors reference](https://docs.rocketverifier.com/errors) lists every API error code.

## Retries and timeouts

- **Rate limits (429):** retried up to `WithMaxRetries` times, waiting for the `Retry-After` seconds, or 60 seconds when the header is missing. See [rate limits](https://docs.rocketverifier.com/rate-limits).
- **Timeouts and network errors:** retried with 1, 2 and 3 second waits.
- **Other errors:** returned straight away.
- **Context:** a cancelled or expired `ctx` stops the call and any wait between retries.
- **Idempotency:** every POST, PUT and PATCH sends an `Idempotency-Key` reused across retries of that call.

## Next steps

- [Reading results](https://docs.rocketverifier.com/results)
Every status and sub_status, what it costs and what to do with it.
- [All SDKs](https://docs.rocketverifier.com/sdks)
Compare the Node.js, Python, Go, PHP and Ruby libraries and the CLI.

## Frequently asked questions

### Does the Go SDK have dependencies?

No. It uses only the Go standard library and needs Go 1.21 or later.

### Is the client safe for concurrent use?

Yes. Create one `*rocketverifier.Client` and share it across goroutines. OAuth refresh is serialized, so concurrent calls share a single refresh.

### How do I check for a specific error?

Use `errors.Is(err, rocketverifier.ErrInsufficientCredits)` and the other sentinel errors, or `errors.As` into `*rocketverifier.Error` to read `Code`, `StatusCode` and `RetryAfter`.

### Which errors does the SDK retry?

Rate limits (429), timeouts and network errors, up to `WithMaxRetries` times (3 by default). Other 4xx and 5xx responses are returned straight away.
